validation for dropdown in MVC3

。_饼干妹妹 提交于 2019-12-13 03:55:58

问题


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>   


来源:https://stackoverflow.com/questions/21306008/validation-for-dropdown-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!