您可以用数据注释属性来修饰模型属性,使您能够执行一些验证逻辑。下面是一个简单的例子:
模型:
public class Group
{
[Required]
public string GroupName { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Group());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Group group)
{
// Remark: You don't need the FormCollection as argument to this action,
// leave the default model binder do the job - it will also work
// for the ContactInfo property as long as you name your text fields
// appropriately. For example Html.TextBox("ContactInfo.Email", Model.ContactInfo.Email)
return View(group);
}
}
观点:
<% using (Html.BeginForm()) { %>
<label for="GroupName">Group Name:</label>
<%= Html.TextBox("GroupName", Model.GroupName) %>
<%= Html.ValidationMessage("GroupName", "group") %>
<input type="submit" value="Post" />
<% } %>
由您来决定数据注释是否足以满足您的情况,但请记住,如果您需要执行更高级的验证方案,您可以查看第三方框架,如
FluentValidation
和
xVal
.