[英]Form Values from Model Not Updating in View After Post
I believe I'm missing something quite trivial here, but I'm not spotting it. 我相信我在这里错过了一些琐碎的事情,但是我没有发现它。 I have a
Post
method, which modifies a Model property. 我有一个
Post
方法,可以修改Model属性。 I then want that model property to reflect the new property value. 然后,我希望该模型属性反映新的属性值。 So here are the pieces:
所以这是碎片:
Controller: 控制器:
[HttpPost]
public ActionResult Index(HomeModel model)
{
ModelState.Clear(); //Didn't help
model.MyValue = "Hello this is a different value";
return View(model);
}
Model: 模型:
public class HomeModel
{
[Display(Name = "My Message")]
public string MyValue { get; set; }
}
View: 视图:
@model MyApp.Models.HomeModel
@{
ViewBag.Title = "My MVC App";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
<h5>Hello</h5>
<input id="SendMessage" type="submit" value="Send Message"/>
@Html.LabelFor(m => m.MyValue)
}
</div>
</body>
</html>
When I debug the controller I can see the updated model, but my LabelFor
always has the Display
attribute as opposed to the value I provided of "Hello this is a different value"
. 当我调试控制器时,我可以看到更新的模型,但是我的
LabelFor
始终具有Display
属性,而不是我提供的"Hello this is a different value"
。 What am I missing here that this label is not updated? 我在这里想念的是这个标签没有更新吗?
@Html.LabelFor
displays your property name (or the name defined in your DisplayAttribute
), whereas @Html.DisplayFor
displays your property content. @Html.LabelFor
显示您的属性名称(或在DisplayAttribute
定义的名称),而@Html.DisplayFor
显示您的属性内容。 If your want "Hello this is a different value"
displays, replace @Html.LabelFor
by @Html.DisplayFor
如果要显示
"Hello this is a different value"
,请用@Html.LabelFor
替换@Html.DisplayFor
The html helper look at the ModelState
when binding their values and then in the model. html帮助程序在绑定它们的值时然后在模型中查看
ModelState
。
So if you intend to modify any of the POSTed values inside your controller action make sure you remove them from the model state first: 因此,如果您打算在控制器操作中修改任何POSTed值,请确保首先从模型状态中将其删除:
ModelState.Remove("PropertyName");
Read this MVC 3 - Html.EditorFor seems to cache old values after $.ajax call 阅读此MVC 3-Html.EditorFor似乎在$ .ajax调用后缓存旧值
That's the purpose of LabelFor
, display the property name. 这就是
LabelFor
的目的,显示属性名称。 Either use EditorFor
or just access the model property directly inside a label
tag it to your view 使用
EditorFor
或直接在label
内直接访问模型属性,将其标记为视图
<h5>Hello</h5>
<input id="SendMessage" type="submit" value="Send Message"/>
<label>@Model.MyValue</label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.