DropDownListFor
不会抛出验证错误消息。它不允许提交页面但不会抛出错误。除了下拉列表外,还会显示其他验证消息。
public class CallLogViewModel
{
[Required(ErrorMessage = "please select")]
[Display(Name = "Details of Issue/Incident")]
public IEnumerable<IssueCategory> IssueDetails { get; set; }
public int SelectedIssue { get; set; }
public CallLogViewModel()
{
HomeRepository hr = new HomeRepository();
IssueDetails = hr.GetIssueCategories();//gets the list
}
}
public class IssueCategory
{
public int UniqueId { get; set; }
public string Issue { get; set; }
}
Controller.cs
public ActionResult Index()
{
var viewModel = new CallLogViewModel();
return View(viewModel);
}
查看
<div class="form-group">
@Html.LabelFor(model => model.IssueDetails, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.DropDownListFor(model => model.SelectedIssue, new SelectList(Model.IssueDetails, "UniqueId", "Issue", Model.SelectedIssue), "Please Select",new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.IssueDetails,"", new { @class = "text-danger" })
</div>
</div>
的Web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
答案 0 :(得分:0)
您将ValidationMessageFor()
应用于SelectList
,而非绑定到的属性。
将模型更改为
public class CallLogViewModel
{
public IEnumerable<IssueCategory> IssueDetails { get; set; }
// Apply the attributes to the property your binding to
[Required(ErrorMessage = "please select")]
[Display(Name = "Details of Issue/Incident")]
public int SelectedIssue { get; set; }
....
并更改视图以将标签和验证消息绑定到SelectedIssue
属性
<div class="form-group">
@Html.LabelFor(m => m.SelectedIssue, new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.DropDownListFor(m => m.SelectedIssue, new SelectList(Model.IssueDetails, "UniqueId", "Issue"), "Please Select",new { @class = "form-control" } )
@Html.ValidationMessageFor(m => m.SelectedIssue, "", new { @class = "text-danger" })
</div>
</div>
另请注意,SelectList
构造函数的第4个参数不是必需的(Selected
SelectListItem
DropDownListFor()
属性被public IEnumerable<SelectListItem> IssueDetails { get; set; }
方法忽略。但是因为您使用了视图模型,你的属性应该是@Html.DropDownListFor(m => m.SelectedIssue, Model.IssueDetails, "Please Select", new { @class = "form-control" } )
(你在GET方法中填充,视图就是
execute()