简体   繁体   English

asp.net mvc 5 DropDownListFor始终为空

[英]asp.net mvc 5 DropDownListFor with empty first item is always Required

I have a viewmodel class that contains the following: 我有一个包含以下内容的viewmodel类:

public class PersonalDetailViewModel
{
    public int TitleOfCourtesyId { get; set; }

    [Display(Name = "Title of Courtesy")]
    public IEnumerable<SelectListItem> TitlesOfCourtesy { get; set; }

    public PersonalDetailViewModel(){

        using(var db = new MyDbContext())
        {
            TitlesOfCourtesy = db.TitleOfCourtesies.ToList().Select(i => 
                                                new SelectListItem
                                                {
                                                    Text = i.TitleOfCourtesyName,
                                                    Value = i.ID.ToString(),
                                                    Selected = i.ID == TitleOfCourtesyId
                                                });
        }            

    }
}

This works fine and loads all the values from the DB into the TitlesOfCourtesy object. 这可以正常工作,并将所有值从数据库加载到TitlesOfCourtesy对象中。 Please note that neither TitleOfCourtesyId nor TitlesOfCourtesy is marked as Required . 请注意, TitleOfCourtesyIdTitlesOfCourtesy标记为Required

My view has the following code to bind this list to a drop down list: 我的视图具有以下代码将此列表绑定到下拉列表:

@Html.ValidationSummary()
<div class="form-group">
    @Html.LabelFor(m => m.TitlesOfCourtesy, new { @class = "control-label col-sm-4" })

    <div class="col-sm-4">
        @Html.DropDownListFor(m => m.TitleOfCourtesyId, Model.TitlesOfCourtesy, "Select", new { @class = "form-control", autofocus = ""})
    </div>
    <div class="col-sm-4">

    </div>
</div>

But on the Submit button, the client validation prompts me as The TitleOfCourtesyId field is required. 但是在“ Submit按钮上,客户端验证提示我,因为The TitleOfCourtesyId field is required. . Why? 为什么? I have not mentioned it as Required in my code. 我在代码中没有提到它为Required Am I missing something? 我想念什么吗?

Thanks for reading. 谢谢阅读。

change it to int? 将其更改为int? , (since int has a default value as zero) ,(因为int的默认值为零)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM