-->

validation for dropdown in MVC3

2019-09-17 19:25发布

问题:

I am validating a form using default MVC validation technique as follows:

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

This is working fine for textboxes. When i applied the same for dropdown this is not working.

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

How to validate for a dropdown in mvc3.Default will be "--Select--"

回答1:

I think you might need to use @Html.DropDownListFor() in order for the model binding for validation to work, which means the SelectList will have to made by the model.

Typically this is how I set it up:

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