【发布时间】:2011-12-11 08:28:09
【问题描述】:
This Question 类似,但接受的答案在服务器端解决,我对客户端解决方案感兴趣。
给定这个 ViewModel
public class MyViewModel
{
public string ID { get; set; }
[Required(ErrorMessage = "I DEMAND YOU MAKE A CHOICE!")]
[Display(Name = "Some Choice")]
public int SomeChoice{ get; set; }
[Required(ErrorMessage = "I DEMAND YOU MAKE A CHOICE!")]
[Display(Name = "Keyword")]
public string Keyword { get; set; }
}
剃须刀
<div>
@Html.LabelFor(model => model.SomeChoice, new { @class = "label" })
@Html.DropDownListFor(model => model.SomeChoice, (SelectList)ViewBag.SomeChoice, "Select...")
@Html.ValidationMessageFor(model => model.SomeChoice)
</div>
并假设 ViewBag.SomeChoice 包含一个选择列表
渲染的 html 没有得到 data-val="true" data-val-required="I DEMAND YOU MAKE A CHOICE!"其中的属性,如 @Html.EditorFor(model => model.Keyword) 或 @Html.TextBoxFor 将呈现。
为什么?
像这样添加 class= "required"
@Html.DropDownListFor(model => model.SomeChoice, (SelectList)ViewBag.SomeChoice, "Select...", new { @class = "required" })
它使用 jQuery Validation 类语义并在提交时阻止但不显示消息。这种事情我可以做
@Html.DropDownListFor(model => model.SomeChoice, (SelectList)ViewBag.SomeChoice, "Select...", new Dictionary<string, object> { { "data-val", "true" }, { "data-val-required", "I DEMAND YOU MAKE A CHOICE!" } })
这将把正确的属性放在那里,并阻止提交并显示消息,但没有利用我的 ViewModel 上的 RequiredAttribute ErrorMessage
那么有没有人写过一个 DropDownListFor,它在验证方面的行为与其他 HtmlHelper 一样?
编辑 这是我的确切代码
在 HomeController.cs 中
public class MyViewModel
{
[Required(ErrorMessage = "I DEMAND YOU MAKE A CHOICE!")]
[Display(Name = "Some Choice")]
public int? SomeChoice { get; set; }
}
public ActionResult About()
{
var items = new[] { new SelectListItem { Text = "A", Value = "1" }, new SelectListItem { Text = "B", Value = "2" }, new SelectListItem { Text = "C", Value = "3" }, };
ViewBag.SomeChoice = new SelectList(items,"Value", "Text");
ViewData.Model = new MyViewModel {};
return View();
}
关于.cshtml
@using Arc.Portal.Web.Host.Controllers
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(model => model.SomeChoice)
@Html.DropDownListFor(model => model.SomeChoice, (SelectList)ViewBag.SomeChoice, "Select...")
@Html.ValidationMessageFor(model => model.SomeChoice)
</div>
<button type="submit">OK</button>
}
这是渲染的代码
<form action="/Home/About" method="post"> <div>
<label for="SomeChoice">Some Choice</label>
<select id="SomeChoice" name="SomeChoice"><option value="">Select...</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<span class="field-validation-valid" data-valmsg-for="SomeChoice" data-valmsg-replace="true"> </span>
</div>
<button type="submit">OK</button>
</form>
它回发给我的控制器...这不应该发生
【问题讨论】:
标签: asp.net-mvc-3 validation razor html-helper