当应该为true时,ModelState.IsValid返回false

时间:2010-11-08 19:03:34

标签: validation asp.net-mvc-2

我有一个非常简单的MVC 2表单。它有两个下拉列表,用户和角色。无论我选择什么,员工下拉列表都会通过验证,而角色下拉列表则不会。虽然我计划实现一个,但没有默认的“空”选项,这就是我需要验证才能工作的原因。它无法进行客户端和服务器验证。我只是不明白为什么一个人会工作,一个人不会!

表格:

<% using (Html.BeginForm()) {%>

    <%:Html.ValidationSummary(true) %>
    <%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>

    <p>
        <input type="submit" value="Add New User" />
    </p>

    <% } %>

<% Html.EndForm(); %>

编辑模板:

<tr>
    <td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.UserId) %>
            <%: Html.RequiredMarkFor(model => model.UserId) %>
        </div>   
    </td>    
    <td>    
    <div class="editor-field">
        <%: Html.DropDownListFor(model => model.UserId, new SelectList(ViewData["AllEmployees"] as IEnumerable, "UserId", "DisplayName", Model.UserId)) %>
        <%: Html.ValidationMessageFor(model => model.UserId>
    </div>    
    </td>       
</tr>     

<tr>
    <td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.AccessLevel)%>
            <%: Html.RequiredMarkFor(model => model.AccessLevel)%>
        </div>   
    </td>    
    <td>    
        <div class="editor-field">
            <%: Html.DropDownListFor(model => model.AccessLevel, new SelectList(ViewData["RoleList"] as IEnumerable, Model.AccessLevel))%>
            <%: Html.ValidationMessageFor(model => model.AccessLevel)%>
        </div>    
    </td>       
</tr> 

元数据:

    [DisplayName("Employee")]
    [Required(ErrorMessage = "Please select an employee.")]
    [StringLength(8, ErrorMessage = "User Id must be less than 8 characters.")]
    [DisplayFormat(ConvertEmptyStringToNull = false,
                            HtmlEncode = true)]
    [DataType(DataType.Text)]
    public object UserId { get; set; }


    // Validation rules for Access Level
    [DisplayName("Role")]
    [Required(ErrorMessage = "Please select the role for this user.")]
    [StringLength(15, ErrorMessage = "Role must be under 15 characters.")]
    [DisplayFormat(ConvertEmptyStringToNull = false,
                            HtmlEncode = true)]
    [DataType(DataType.Text)]
    public object AccessLevel { get; set; }

获取行动:

    List<String> roles = (from o in txDB.Users
                                      select o.AccessLevel).Distinct().ToList(); 

    var viewModel = new UserViewModel
    {
        User = new User(),
        AllEmployees = empList,
        RoleList = roles
    };
    return View(viewModel);

邮政行动:

    [HttpPost]
    [AuthorizeAttribute(Roles="Administrator")]
    public ActionResult Create(User user)
    {
        if(!ModelState.IsValid)
        {
            //ModelState is invalid
            return View(new User());
        }
        try
        {
           //do stuff
        }
    }

必需助手方法(来自Define markup for [Required] fields in View in ASP.NET MVC 2.0):

    public static string RequiredMarkFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        if(ModelMetadata.FromLambdaExpression(expression, helper.ViewData).IsRequired)
            return "*";
        else
            return string.Empty;
    } 

2 个答案:

答案 0 :(得分:2)

Post方法应该如下,以获得服务器端验证...

[HttpPost]
[AuthorizeAttribute(Roles="Administrator")]
public ActionResult Create(User user)
{
    if(!TryUpdateModel(user))
    {
       // Model is INVALID
       return View(user);
    }
    else
    {
        // ModelState is VALID
        // Do stuff
    }
}

else可能是多余的,这取决于你正在做什么,但这应该让你去。 在您需要的<% using Html.BeginForm() %>上方的视图中

<% Html.EnableClientValidation(); %>

您还需要引用我认为的脚本,MicrosoftAjax和MicrosoftMvcValidation

答案 1 :(得分:1)

首先:你有两个结束表格标签

如果您使用

<% using (Html.BeginForm()) {%>
<% } %>

你不需要使用这个

<% Html.EndForm(); %>

关于验证问题,您只使用编辑器作为您的用户属性,这是唯一一个被模型绑定器绑定的用户属性

<%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>

尝试使用EditorForModel替换以前的代码,因为您的编辑器模板适用于模型类。

所以你的表格应该改变

<% using (Html.BeginForm()) {%>

    <%:Html.ValidationSummary(true) %>
    <table>
        <%:Html.EditorForModel()%>
    </table>
    <p>
        <input type="submit" value="Add New User" />
    </p>
<% } %>

你已经完成了!