验证MVC3中的下拉列表

时间:2014-01-23 10:51:40

标签: asp.net-mvc html.dropdownlistfor asp.net-mvc-validation

我正在使用默认MVC验证技术验证表单,如下所示:

<div class="editor-label">
        @Html.LabelFor(model => model.Company_Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Company_Name)
        @Html.ValidationMessageFor(model => model.Company_Name, "Company Name is required")
    </div>

这适用于文本框。当我将其应用于下拉列表时,这不起作用。

 <div class="editor-label">
        @Html.LabelFor(model => model.State_Code, "State")
    </div>
    <div class="editor-field">
        @Html.DropDownList("State_Code", "--Select--")
        @Html.ValidationMessageFor(model => model.State_Code,"State is required")
    </div>

如何验证mvc3.Default中的下拉列表将是“--Select - ”

1 个答案:

答案 0 :(得分:2)

我认为您可能需要使用@ Html.DropDownListFor()才能使验证的模型绑定起作用,这意味着SelectList必须由模型生成。

通常这就是我设置它的方式:

//Libary of commom stuff
public class WebLibrary
{
    public SelectList StatesAndProvinces()
    {
        return new SelectList(
            new List<SelectListItem> { 
                new SelectListItem{ Value = "AR", Text = "Alabama" },
                new SelectListItem{ Value = "AK", Text = "Alaska" }
        }, "Value", "Text");
    }
}

//ViewModel
public class FormModel
{
    public SelectList stateDropdown { get; set; }
    public string State_Code { get; set; }
    public string Company_Name { get; set; }

    public FormModel()
    {
        stateDropdown = WebLibrary.StatesAndProvinces();
    }
}

//View
<div class="editor-field">
    @Html.DropDownListFor(model => model.State_Code, Model.stateDropdown, new { @class="dropdown" })
    @Html.ValidationMessageFor(model => model.State_Code,"State is required")
</div>