public class HomeController : Controller
{
public ActionResult Create()
{
return View("Create");
}
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Role role)
{
if (ModelState.IsValid)
{
return this.View("RoleList");
}
return this.View(role);
}
}
public partial class Role
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty(RoleID))
yield return new RuleViolation("RoleID不能为空", "RoleID");
yield break;
}
}
public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation(string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="tabDiv" style="margin: 0px 6px 6px 6px;">
<h2 style="margin: 5px 20px 5px 0px;">
CreateRole</h2>
<%=Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm())
{%>
<table>
<tr>
<td align="right" width="10%">
<label for="RoleID">
RoleID:</label>
</td>
<td>
<%= Html.TextBox("RoleID")%>
<%=Html.ValidationMessage("RoleID","*")%>
</td>
</tr>
<tr>
<td align="right" width="10%">
<label for="CompanyID">
CompanyID:</label>
</td>
<td>
<%= Html.TextBox("CompanyID")%>
</td>
</tr>
</table>
<div>
<input type="submit" value="确认" />
<div style="float: right;">
<%=Html.ActionLink("Back to RoleList", "RoleList") %>
</div>
</div>
<% }
%>
</div>
</asp:Content>
那位高手帮忙看看,怎么验证不出来,并且为什么ModelState.IsValid总是为true?当然,我没有用强类型进行绑定。
Role 你的role类添加了特性标签没。。。