DropDownListFor Unobtrusive Validation Required不获取正确的属性

时间:2011-10-19 22:24:58

标签: asp.net-mvc-3 validation razor html-helper

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 =“我要求你做出选择!”其中的属性如@ Html.EditorFor(model =&gt; 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,其行为与其他HtmlHelpers的验证方式相同?

修改的 这是我的精确代码

在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();
    }

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

它回发给我的控制器......这不应该发生

3 个答案:

答案 0 :(得分:5)

只需在您将视图模型绑定到下拉列表的属性上使用可以为空的整数:

[Required(ErrorMessage = "I DEMAND YOU MAKE A CHOICE!")]
[Display(Name = "Some Choice")]
public int? SomeChoice { get; set; }  

另外,为了获得适当不引人注目的HTML5 data- *属性,下拉列表必须位于表单内:

@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, new { @class = "label" })
        @Html.DropDownListFor(
            model => model.SomeChoice, 
            Model.ListOfChoices, 
            "Select..."
        )
        @Html.ValidationMessageFor(model => model.SomeChoice)
    </div>

    <button type="submit">OK</button>
}

另外你会注意到我摆脱了ViewBag(我根本无法忍受)并用你视图模型上的相应属性替换它,它将包含下拉列表的可能选项。

答案 1 :(得分:3)

我遇到了同样的问题。并注意到当从ViewBag或ViewData填充dropDownList时会发生这种情况。如果你愿意的话 @ Html.DropDownListFor(model =&gt; model.SomeChoice,Model.SomeChoice,“Select ...”),如上例所示,将写入验证属性。

答案 2 :(得分:0)

那些在Kendo下拉列表中寻找相同行为的人,请添加&#39; required&#39;在你的代码中。

@(Html.Kendo().DropDownListFor(m => m)
    .Name("FeatureId").BindTo((System.Collections.IEnumerable)ViewData[CompanyViewDataKey.Features])
    .DataValueField("Id")
    .DataTextField("Name")
    .OptionLabel("--Select--")
    .HtmlAttributes(new { title="Select Feature", required="required"})

viewmodel中的

[必需]属性对我不起作用,但在Htmlattributes中添加了上述内容。希望这有助于某人。