我使用4個字符串字段聲明模型。其中3個是隻讀的形式:MVC模型不會以表格形式存在
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不保存模型類的其他成員嗎?如果這是預期的 - 有沒有辦法重新獲得這些?或者我需要返回到我的數據庫,使用舊值填充模型,然後使用表單模型中的新值?
想要從模型中讀取「只讀」字段的有效性被質疑。這是公平的 - 但是如果我發現有關發佈數據的可疑信息,顯示屏幕,而不必重新讀取數據庫中的數據?
[只讀(true)] 表示該屬性是隻讀的,因此不會與回發的值綁定 –