当表单处于编辑模式时,使该字段成为隐藏属性,并具有您在控制器中评估的“默认”值。如果您根本不想在表单上显示属性并且仍然需要它,那么您不应该使用“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”