ASP.NET MVC 5.1自定义EditorTemplate并添加额外的htmlAttributes(反馈请求)

时间:2016-06-29 16:49:30

标签: asp.net-mvc twitter-bootstrap

我正在寻找关于我创建的自定义EditorTemplates的一些反馈。我的自定义EditorTemplates的目的是确保始终存在Bootstrap 3 CSS类form-control,以及一些适当的HTML属性,具体取决于视图模型属性的数据类型。

但是,我仍然希望能够在实际使用EditorTemplate时添加其他CSS类或各种HTML属性。例如,当我使用

@Html.EditorFor(model => model.Something, new { htmlAttributes = new { @class = "datepicker" } })

我希望得到与此类似的HTML

<input type="text" class="datepicker form-control" id="Something" name="Something" />

我的自定义string EditorTemplate的当前代码如下(其他数据类型当然也是类似的)。这有效,但我想知道我是否太复杂了?任何反馈都将不胜感激。

@{
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);

    if (!attributes.ContainsKey("placeholder") &&
        !string.IsNullOrWhiteSpace(ViewData.ModelMetadata.Watermark))
    { attributes.Add("placeholder", ViewData.ModelMetadata.Watermark); }

    if (!attributes.ContainsKey("aria-required") &&
        ViewContext.ViewData.ModelMetadata.IsRequired)
    { attributes.Add("aria-required", "true"); }

    // If the attributes dictionary already has a class attribute defined
    if (attributes.ContainsKey("class"))
    // Add the bootstrap class to it
    { attributes["class"] += " form-control"; }
    else
    // Create class attribute
    { attributes.Add("class", "form-control"); }
}
@Html.TextBox(string.Empty, ViewData.TemplateInfo.FormattedModelValue, attributes)

0 个答案:

没有答案