验证在下拉MVC3 [英] validation for dropdown in MVC3
本文介绍了验证在下拉MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我验证使用默认的MVC验证技术形式如下:
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>
如何验证在mvc3.Default下拉会 - 选择 -
How to validate for a dropdown in mvc3.Default will be "--Select--"
推荐答案
我想你可能需要@ Html.DropDownListFor(),以用于模型验证工作的结合,这意味着选择列表必须由取得该模型。
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>
这篇关于验证在下拉MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文