让模型处理自己的验证的能力使我开始使用 MVC 2 预览版。到目前为止,我喜欢验证方案的简单性。然而,我遇到了障碍。这种验证风格适用于简单的视图模型对象。例如,如果我有一个名为car的模型对象,并且我希望创建一个视图来创建一辆新车:
- - -模型 - - - -
public class Car
{
public string Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
}
- - -控制器 - - - - -
public class CarController : Controller
{
public ActionResult Create()
{
Car myCar = new Car();
return View("Create", myCar);
}
[HttpPost]
public ActionResult Create(Car myCar)
{
if (!ModelState.IsValid)
{
return View("Create", myCar);
}
//Do something on success
return View("Index");
}
}
- - - -看法 - - - - - - -
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Car>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<%
using (Html.BeginForm()) {%>
<fieldset>
<legend>Edit User Profile</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id", Model.Id)%>
<%= Html.ValidationMessage("Id") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name)%>
<%= Html.ValidationMessage("Name") %>
</p>
<p>
<label for="Color">Color:</label>
<%= Html.TextBox("Color", Model.Color)%>
<%= Html.ValidationMessage("Color") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
</asp:Content>
这就像一个魅力。但并不是我所有的观点或模型对象都是简单的。我可能有一个汽车模型对象,例如:
- - -模型 - - - -
public class PaintScheme
{
public int Red { get; set; }
public int Blue { get; set; }
public int Green { get; set; }
}
public class Car
{
public string Id { get; set; }
public string Name { get; set; }
public PaintScheme Paint{ get; set; }
}
- - - -看法 - - - - - - -
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Car>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<%
using (Html.BeginForm()) {%>
<fieldset>
<legend>Edit User Profile</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id", Model.Id)%>
<%= Html.ValidationMessage("Id") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name)%>
<%= Html.ValidationMessage("Name") %>
</p>
<p>
<label for="Red">Color Red:</label>
<%= Html.TextBox("Red", Model.Paint.Red)%>
<%= Html.ValidationMessage("Red") %>
</p>
<p>
<label for="Blue">Color Blue:</label>
<%= Html.TextBox("Blue", Model.Paint.Blue)%>
<%= Html.ValidationMessage("Blue") %>
</p>
<p>
<label for="Green">Color Green:</label>
<%= Html.TextBox("Green", Model.Paint.Green)%>
<%= Html.ValidationMessage("Green") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
</asp:Content>
当我将PaintScheme属性添加到我的视图时,它们不会与传递给我的控制器操作的“myCar”对象一起使用。有没有办法解决这个问题,而不必从表单集合中重建对象然后检查 ModelState?