错误:字段ID必须是数字。在@Html.DropDownListFor方法中

时间:2013-06-01 08:22:10

标签: asp.net-mvc asp.net-mvc-4 jquery-validate unobtrusive-validation

我的模特:

public class ViewRequestModel
{
    [Required(ErrorMessage = "some")]
    [Display(Name = "some")]
    public int RequestType { get; set; }
}

我的控制员:

[HttpPost]
    [Authorize(Roles = "P")]
    public PartialViewResult ViewRequests(ViewRequestModel model)
    {
        string vn = "";
        switch (model.RequestType)
        {
            ...
        }

        return PartialView(vn);
    }

我的观点:

@{
    var reqTypes = new List<ListItem> { new ListItem { Text = "t1", Value = "1" }, 
       new ListItem { Text = "t2", Value = "2" },
       new ListItem { Text = "t3", Value = "3" } };
 }
 @Html.DropDownListFor(model => model.RequestType, new SelectList(reqTypes), new { id = "ddlType" })

 @Html.ValidationMessageFor(model => model.RequestType)

当我尝试发布表单时,jquery验证会阻止它并显示错误The field RequestType must be a number

哪里是我的错?

1 个答案:

答案 0 :(得分:4)

  

我的错误在哪里?

您正在将一些经典WebForms类(ListItem)与ASP.NET MVC混合使用。这样做的结果是下拉列表中的<option>元素没有值属性。因此,没有任何内容提交到表单,验证显然会失败。

以下是填充下拉列表的正确方法:

var reqTypes = new[]
{ 
    new SelectListItem { Text = "t1", Value = "1" }, 
    new SelectListItem { Text = "t2", Value = "2" },
    new SelectListItem { Text = "t3", Value = "3" } 
};

@Html.DropDownListFor(
    model => model.RequestType, 
    reqTypes, 
    new { id = "ddlType" }
)

从这个例子中可以看出,我使用的是专门用于ASP.NET MVC的SelectListItem类。这会产生:

<select data-val="true" data-val-number="The field some must be a number." data-val-required="some" id="ddlType" name="RequestType">
    <option selected="selected" value="1">t1</option>
    <option value="2">t2</option>
    <option value="3">t3</option>
</select>

你的代码生成:

<select data-val="true" data-val-number="The field some must be a number." data-val-required="some" id="ddlType" name="RequestType">
    <option>t1</option>
    <option>t2</option>
    <option>t3</option>
</select>

差异很明显。