C# 发帖后查看不更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9645479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
View not updating after post
提问by Captain0
I have a controller method CreateOrUpdate, this method is supposed to save the car to the database and then return as normal.
我有一个控制器方法 CreateOrUpdate,这个方法应该将汽车保存到数据库中,然后正常返回。
public ActionResult CreateOrUpdate(int ID = 0)
{
Car car = new Car(ID);
}
[HttpPost]
public ActionResult CreateOrUpdate(Car car)
{
car.Save();
return View(car);
}
In the theCar.Save() method, i set the id for the car, with whatever the id will be in the database after the car is saved (When doing an insert I use SCOPE_IDENTITY(), the save method works well, and if i debug and watch the values for car after the Save() is called, the id is correct. But when the View is rendered the ID is 0 in the view.
在 theCar.Save() 方法中,我为汽车设置了 id,无论汽车保存后数据库中的 id 是什么(在执行插入时我使用 SCOPE_IDENTITY(),save 方法运行良好,如果我在调用 Save() 后调试并观察 car 的值,id 是正确的。但是当视图呈现时,视图中的 ID 为 0。
Could anyone please help me,and tell me why this would happen. Am I not suppose to change the Model for the view in the HTTP POST method ? Should i Rather redirect to the original CreateOrUpdate() method if the save was successful.
任何人都可以帮助我,并告诉我为什么会发生这种情况。我不应该在 HTTP POST 方法中更改视图的模型吗?如果保存成功,我应该重定向到原始的 CreateOrUpdate() 方法。
采纳答案by Mason
it should be the ModelState problem. if you use Htmlhelper to Display id value. Default HtmlHelper display ModelState value not Model. Try display model value in view
应该是 ModelState 的问题。如果您使用 Htmlhelper 来显示 id 值。默认 HtmlHelper 显示 ModelState 值而不是 Model。尝试在视图中显示模型值
<td>
@Model.id
</td>
or Clean ModelState Value in controller
或清除控制器中的 ModelState 值
ModelState.Clear();
or reset id value after SaveChange.
或在 SaveChange 后重置 id 值。
theCar.Save();
ModelState["id"].Value = theCar.id
return View(theCar);
回答by Captain0
I added ModelState.Clear()to my HttpPost Controller method, as seen in this post Html helpers get data from model state and not from model if you return the same view after form post. to get updated data in the view use post redirect get pattern or ModelState.Clear()
and it solved the problem.
我添加ModelState.Clear()到我的 HttpPost 控制器方法中,如这篇文章中所见,如果您在表单发布后返回相同的视图,Html 帮助程序从模型状态而不是从模型中获取数据。要在视图中使用 post redirect get pattern 或 ModelState.Clear() 来获取更新的数据
,它解决了这个问题。
Thanks
谢谢
回答by Michael Tranchida
I didn't want to clear the ModelState because I needed to display errors, so I went with
我不想清除 ModelState 因为我需要显示错误,所以我去了
ValueProviderResult vpr = new ValueProviderResult("", null, System.Globalization.CultureInfo.CurrentCulture);
ModelState["id"].Value = vpr;

