[英]MVC3 Partial model validation
我有麻煩了,請你幫忙。
我有一堂簡單的課
public class Test
{
[Key]
public string a { get; set; }
[Required]
public string c { get;set; }
public string b { get; set; }
}
我創建了一個簡單的表單來提交新的實體實例,它可以工作。 我在編輯時遇到麻煩:編輯表單顯示'a'和'b'屬性。 由於“ c”只能在新實體中提交,並且不能顯示(不要問為什么),因此在我的更新方法中:
public ActionResult Edit(Test t)
{
if (ModelState.IsValid)
{
//get the m instance
UpdateModel(m,//other params);
ValidateModel(m);
}
//saving code
}
顯然, ModelState.IsValid
始終為false(因為“ c”是必需的”,但為null),並且UpdateModel
引發Exception(出於相同的原因)。 我如何對MVC3說“不要僅在此控制器方法中驗證此字段?” 顯然,我不會在模型類中編寫未驗證的字段! 我只需要更新'b'屬性。 謝謝。
最簡單的方法是為此局部視圖創建另一個視圖模型。
為此視圖創建另一個視圖模型,並針對該視圖模型而不是實體進行驗證。
@{
object htmlAttribute = null;
if(Model.Id > 0)
{
htmlAttribute = new { disabled = "disabled" };
}
}
@Html.TextBoxFor(model => model.C, htmlAttributes)
禁用時,將不驗證C
當表單處於“編輯”模式時,使該字段成為具有在控制器中評估的“默認”值的隱藏屬性。 如果您根本不想在表單上顯示該屬性,但仍然需要它,那么您就不應該使用“ ModeState.IsValid”來進行自己的驗證。
隱藏屬性的示例:
控制者
public ActionResult Index() {
return View();
}
public ActionResult Edit(string id) {
return View((string.IsNullOrEmpty(id)) ? new Test { a = "new" } : FakeRepository.Data(id));
}
[HttpPost]
public ActionResult Edit(Test model) {
if (ModelState.IsValid) {
if (model.a == "new") {
//Create a new record
} else {
//Update Record
}
return RedirectToAction("Index");
}
return View(model);
}
public static class FakeRepository {
public static Test Data(string a) {
return new Test {
a = a,
b = "B",
c = "C"
};
}
}
實體
public class Test {
[Key]
[Display(Name="A Property")]
public string a { get; set; }
[Required]
[Display(Name = "C Property")]
public string c { get; set; }
[Display(Name = "B Property")]
public string b { get; set; }
}
視圖
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Test</legend>
@Html.HiddenFor(model => model.a)
@if (Model.a != "new") {
@Html.HiddenFor(model => model.c)
} else {
<div class="editor-label">
@Html.LabelFor(model => model.c)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.c)
@Html.ValidationMessageFor(model => model.c)
</div>
}
<div class="editor-label">
@Html.LabelFor(model => model.b)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.b)
@Html.ValidationMessageFor(model => model.b)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
現在 :
... /編輯/某些東西會隱藏“ C”
... / Edit /將顯示“ C”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.