【问题标题】:MVC3 Editor template doesn't generate client side validationMVC3 编辑器模板不生成客户端验证
【发布时间】:2013-05-28 21:24:00
【问题描述】:

我有一个问题,基本上我有一个包含很多字段的表单,并且所有字段都有一个必需的属性集,所以当您将其留空并单击“确定”时,您将获得客户端验证并变为红色.它适用于除 EditorTemplate 之外的所有内容。

我的模型如下:

public class MyModel
{
  [Required]
  public string Username{get;set;}

  public Location Loc{get;set;}
}

public class Location
{
    [Required]
  public string Loc1{get;set;}
    [Required]
  public string Loc2{get;set;}
}

我的主视图中有以下内容:

@Html.EditorFor(m => m.Location, Model.Location)

这是我的 EditorTemplate:

<tr>
    <td class="editor-label">
        @Html.LabelFor(m => m.Loc1)
    </td>
    <td class="editor-field">
        @Html.DropDownListFor(m => m.Loc1, Model.Locs==null?Enumerable.Empty<SelectListItem>():Model.Locs, "---select--", new { @class = "location-ddl" })
    </td>
    <td>
        @Html.ValidationMessageFor(m => m.Loc1)
    </td>
</tr>

...

经过仔细调查后,我注意到它产生的 HTML 如下:

<select name="Location.Loc1" id="Location_Loc1">

你可以看到它缺少一些客户端验证的属性,通常应该是这样的:

<select name="Loc1" id="Loc1" data-val-required="The Loc1field is required." data-val="true">

我的问题是,为什么编辑器模板没有通过客户端验证生成正确的 html 输出,以及如何解决?

只是为了说明它确实在服务器端工作,因此如果这些选择在服务器端为空,它将被标记为未填写并发回。但是,我仍然想了解 editorform 的行为以及修复它的方法。

谢谢

【问题讨论】:

  • 客户端验证是否适用于UserName 属性?
  • 真的没有人遇到过这种问题吗?

标签: c# asp.net-mvc-3 model editorfor editortemplates


【解决方案1】:

您可以使用Html.GetUnobtrusiveValidationAttributes("Location.Loc1") 来获取验证属性。 请参阅文档here

【讨论】:

    【解决方案2】:

    我觉得Html.GetUnobtrusiveValidationAttributes()的用法应该再详细解释一下。

    假设您的编辑器模板模型是Location,您必须在文件顶部添加以下代码块:

    @{
         IDictionary<string, Object> htmlAttributeValuePairsLoc1 = Html.GetUnobtrusiveValidationAttributes(Html.NameFor(m=>m.Loc1).ToHtmlString());
         htmlAttributeValuePairsLoc1.Add("class","location-ddl");
    
         IDictionary<string, Object> htmlAttributeValuePairsLoc2 = Html.GetUnobtrusiveValidationAttributes(Html.NameFor(m=>m.Loc1).ToHtmlString());
         htmlAttributeValuePairsLoc2.Add("class","location-ddl");
    }
    

    现在您可以将适当的字典注入到您的 HtmlHelpers 中,如下所示:

    <tr>
        <td class="editor-label">
            @Html.LabelFor(m => m.Loc1)
        </td>
        <td class="editor-field">
            @Html.DropDownListFor(m => m.Loc1,
                  Model.Locs??Enumerable.Empty<SelectListItem>(),
                  "---select--",
                  htmlAttributeValuePairsLoc1)
        </td>
        <td>
            @Html.ValidationMessageFor(m => m.Loc1)
        </td>
    </tr>
    

    附: Html.NameFor() 出现在 MVC4 中,但是您可以使用 Reflection 获取属性的名称。

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多