MVC3的DropDownList不能与[必填]类字段类型为int验证? [英] MVC3 DropDownList not validating with [Required] class field as type int?

查看:211
本文介绍了MVC3的DropDownList不能与[必填]类字段类型为int验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法,为什么下面的DropDownList不会必填字段验证为int类型(标题的字段)?

Any idea why the following dropdownlist won't validate with required field as type int (the "Title" field below)?

    [Required]             // This works!
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Required]             // This doesn't work 
    [Display(Name = "Title")]
    public int TitleId { get; set; }



     <div class="editor-label">
        @Html.LabelFor(model => model.Name, "Name")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name, "This can't be blank!")
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.TitleId, "Title")
    </div>
    <div class="editor-field">
         @Html.DropDownListFor(model => model.TitleId, (SelectList)ViewBag.TitleId, String.Empty)
        @Html.ValidationMessageFor(model => model.TitleId)
    </div>

推荐答案

根据这项工作项,当在ViewBag选择列表使用相同的名称有问题的领域客户端验证打破。 (即两者都是 TitleId 你的情况。)

According to this work item, client-side validation breaks when the SelectList in the ViewBag uses the same name as the field in question. (i.e. both are TitleId in your case.)

试试这个:

@Html.DropDownListFor(model => 
    model.TitleId, (SelectList)ViewBag.TitleIdList, String.Empty)

你的SelectList重命名为 TitleIdList 相应。

这篇关于MVC3的DropDownList不能与[必填]类字段类型为int验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆