asp.net-mvc - @Html.DropDownListFor 方法中的错误 : The field ID must be a number.

标签 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; }
}

我的 Controller :

[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 验证会阻止它并显示错误字段 RequestType 必须是数字

我的错误在哪里?

最佳答案

where's my mistake?

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

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

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" }
)

正如您从这个示例中看到的,我正在使用 SelectListItem特定于 ASP.NET MVC 的类。这会生成:

<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>

区别很明显。

关于asp.net-mvc - @Html.DropDownListFor 方法中的错误 : The field ID must be a number.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870685/

相关文章:

jquery - 如何在 ASP.NET MVC 3 中自定义不显眼的验证以符合我的风格?

asp.net-mvc - TFS 构建 2012、ASP.NET MVC 和 MSB3247 : Found conflicts between different versions of same dependent assembly

c# - 如何检查 URL 是否在您的网络应用程序中

c# - CSHTML 文件未加载到 View 之外

c# - web api put 识别查询字符串但不识别正文

jquery-validate - ASP.NET MVC4中的条件验证

asp.net-mvc - 哪个 ORM 支持映射现有数据库?

asp.net-mvc - 如何在 ASP.NET MVC 应用程序中使用多个 View 引擎

c# - CSS 背景图像未显示在 MVC4 的 ActionLink 中

javascript - 未捕获的类型错误 : Object #<error> has no method 'call'