view:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ValidationTest.Models.Movie>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Title">Title:</label>
<%= Html.TextBox("Title") %>
<%= Html.ValidationMessage("Title", "*") %>
</p>
<p>
<label for="Director">Director:</label>
<%= Html.TextBox("Director") %>
<%= Html.ValidationMessage("Director", "*") %>
</p>
<p>
<label for="Remark">Remark:</label>
<%= Html.TextBox("Remark") %>
<%= Html.ValidationMessage("Remark", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection) //传递FormCollection,使用UpdateModel
{
Movie m = new Movie();
//使用UpdateModel方法
UpdateModel<Movie>(m);
if (m.Title.Trim().Length == 0)
{
ModelState.AddModelError("Title", "Title 不能为空!");
}
if (m.Director.Trim().Length == 0)
{
ModelState.AddModelError("Director", "Director 不能为空!");
}
if (!ModelState.IsValid)
{
return View();
}
try
{
//TODO SaveToDB
return Content("OK");
}
catch
{
return View();
}
}
或者:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection) //不使用UpdateModel方法,手动向ModelState集合的System.Web.Mvc.ModelState实例的Value属性赋值。
{
Movie m = new Movie() {
Title = collection["Title"],
Director = collection["Director"],
Remark = collection["Remark"] };
//手动添加数据到ModelState集合
ModelState.Add("Title", new ModelState() {
Value = collection.ToValueProvider()["Title"] });
ModelState.Add("Director", new ModelState() {
Value = collection.ToValueProvider()["Director"] });
ModelState.Add("Remark", new ModelState() {
Value = collection.ToValueProvider()["Remark"] });
if (m.Title.Trim().Length == 0)
{
ModelState.AddModelError("Title", "Title 不能为空!");
}
if (m.Director.Trim().Length == 0)
{
ModelState.AddModelError("Director", "Director 不能为空!");
}
if (!ModelState.IsValid)
{
return View();
}
try
{
//TODO SaveToDB
return Content("OK");
}
catch
{
return View();
}
}
浙公网安备 33010602011771号