我声明了一个包含4个字符串字段的模型。其中3个在表单上是只读的:
public class HomeModel
{
[ReadOnly(true)]
[DisplayName("Service Version")]
public string ServiceVersion { get; set; }
[ReadOnly(true)]
[DisplayName("Session Id")]
public string SessionId { get; set; }
[ReadOnly(true)]
[DisplayName("Visiting from")]
public string Country { get; set; }
[DisplayName("Search")]
public string SearchString { get; set; }
}在填充模型之后,我将其传递给我的表单:
[HttpGet]
public ActionResult Index()
{
var model = new HomeModel
{
Country = "Australia",
SearchString = "Enter a search",
ServiceVersion = "0.1",
SessionId = "76237623763726"
};
return View(model);
}表单的显示如我所料:
<h2>Simple Lookup</h2>
@Html.LabelFor(m=>m.ServiceVersion): @Model.ServiceVersion<br/>
@Html.LabelFor(m=>m.SessionId): @Model.SessionId<br/>
@Html.LabelFor(m=>m.Country): @Model.Country<br/>
<p>
@using(Html.BeginForm())
{
@Html.LabelFor(m => m.SearchString)
@Html.TextBoxFor(m => m.SearchString)
<button type="submit" name="btnSearch">Search</button>
}
</p>但是,当我提交表单并从表单中取回模型时,只填充了SearchString的值。
[HttpPost]
public ActionResult Index(HomeModel model)
{
return View(model);
}其他字段已经“丢失”了,对吗?MVC不保留模型类的其他成员吗?如果这是预期的-有没有办法重新获得这些?或者我是否需要返回到我的数据库,用旧值填充模型,然后使用表单模型中的新值?
从模型中读回“只读”字段的有效性可能会受到质疑。这是公平的-但如果我发现发布的数据有可疑之处,也许我想重新显示屏幕,而不必再次从数据库中重新读取数据?
发布于 2013-03-30 15:22:18
这是正确的行为。只有表单中的元素才会发布到您的操作中。因为它是post表单,所以您的字段应该在表单内部,以便在post方法中获取它们。
更新
此外,如果在视图上将特定字段设为只读,则不能读取操作方法中的特定字段。例如:使用@Html.LabelFor显示。为了让字段返回到您的操作中,如果不编辑字段,则使用@Html.HiddenFor。
https://stackoverflow.com/questions/15716072
复制相似问题