首页 新闻 会员 周边 捐助

为什么我的MVC验证中ModelState.IsValid总是为true?

0
[已关闭问题] 关闭于 2011-02-23 10:43

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?当然,我没有用强类型进行绑定。

 

lhz_belen的主页 lhz_belen | 初学一级 | 园豆:185
提问于:2010-09-28 18:02
< >
分享
所有回答(1)
0

Role 你的role类添加了特性标签没。。。

暗夜流风 | 园豆:204 (菜鸟二级) | 2014-12-18 18:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册