DropDownListFor Unobtrusive验证必需没有得到正确的属性

这个问题是相似的,但接受的答案解决了它的服务器端,我对客户端解决方案感兴趣。

鉴于此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 => 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,就像Validation的其他HtmlHelpers一样行事?

编辑这是我的EXACT代码

在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>

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


只需在要绑定到您的视图模型上的下拉列表上使用可空的整数即可:

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

另外为了获得适当的不显眼的HTML5数据属性,下拉菜单必须位于表单内:

@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 (我简直无法忍受),并用视图模型上的相应属性替换它,这将包含下拉列表的可能选项。


我有同样的问题。 并注意到,当从ViewBag或ViewData填充dropDownList时会发生这种情况。 如果您要编写@ Html.DropDownListFor(model => model.SomeChoice,Model.SomeChoice,“Select ...”),如上面的示例验证属性将被写入。


那些在Kendo下拉列表中寻找相同行为的人,请在您的代码中添加'required'。

@(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中添加了上述内容。 希望这可以帮助某人。

链接地址: http://www.djcxy.com/p/56607.html

上一篇: DropDownListFor Unobtrusive Validation Required Not getting correct attributes

下一篇: Validating Mutiple Attributes