我已經把樣本與你所描述的(我認爲),我能夠得到它的工作:
public class TestController : Controller
{
public ActionResult Foo()
{
return View("IFoo");
}
[HttpPost]
public ActionResult Foo(Foo foo)
{
if (!ModelState.IsValid)
return View("IFoo", foo);
return RedirectToAction("Foo");
}
public ActionResult Bar()
{
return View("IFoo");
}
[HttpPost]
public ActionResult Bar(Bar bar)
{
if (!ModelState.IsValid)
return View("IFoo", bar);
return RedirectToAction("Bar");
}
}
// The Interface - the Required attributes are not
// on the interface, just the concrete classes
public interface IFoo
{
string Name { get; set; }
string Description { get; set; }
}
// Concrete Class 1 - Name is required
public class Foo : IFoo
{
[Required(ErrorMessage="Name is required.")]
public string Name { get; set; }
public string Description { get; set; }
}
// Concrete Class 2 - Description is required
public class Bar : IFoo
{
public string Name { get; set; }
[Required(ErrorMessage = "Description is required.")]
public string Description { get; set; }
}
我再定義一個強類型的視圖:
@model Test.Controllers.IFoo
<h2>Test</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>IFoo</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
當我瀏覽到/ test/foo並點擊保存時,我在名稱上出現驗證錯誤。
當我瀏覽到/ test/bar並點擊Save時,我在Description中出現驗證錯誤。
你是對的。驗證在服務器端工作。但jQuery客戶端驗證不起作用,它看起來不像一個簡單的解決方案,所以我將它標記爲已回答。 – Michael