我有一個模型,裏面有一些屬性/類。現在我想驗證一些東西:ASP.NET MVC驗證。如何使用嵌套類
<% = Html.TextBoxFor(p=>p.Ideas.Title, new { @class = "width_percent_80" }) %>
<% = Html.ValidationMessageFor(model => model.Ideas.Title) %>
但它將文本框命名爲Ideas.Title(而不是標題)。爲什麼?
我有一個模型,裏面有一些屬性/類。現在我想驗證一些東西:ASP.NET MVC驗證。如何使用嵌套類
<% = Html.TextBoxFor(p=>p.Ideas.Title, new { @class = "width_percent_80" }) %>
<% = Html.ValidationMessageFor(model => model.Ideas.Title) %>
但它將文本框命名爲Ideas.Title(而不是標題)。爲什麼?
但它將文本框命名爲Ideas.Title(而不是標題)。爲什麼?
使默認模型綁定能夠成功地結合到:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
if (!ModelState.IsValid)
{
// the model was not valid => redisplay the view
// so that the user can fix his errors
return View(model);
}
// at this stage validation passed => we can access individual properties
// of the view model such as model.Ideas.Title here
...
}
嵌套類會給你一個嵌套的字段名。但是你可以在你的實體.cs文件中添加註釋來覆蓋這個。
例如: 在Ideas.cs文件,
[Column(name: "title")] //<- add this
public string Title{ get; set; }
當然,你需要使用DataAnnotation命名空間。
using System.ComponentModel.DataAnnotations;
它不起作用 –
我需要生成名稱=「標題」,而不是「Ideas.Title」在任何情況下... –
@ user285336,兩種可能性:修改您的視圖模型,並在根部直接包括Title屬性,或寫一個自定義的文本框助手,將這樣做。 Html.TextBoxFor就是你所看到的。 –