MVC 5.1 - 使用自定义编辑器模板在EditorFor中添加Html属性

时间:2014-10-01 10:04:47

标签: asp.net-mvc razor asp.net-mvc-5.1

我可以添加htmlAttributes,如下所示,并在Html

中呈现
@Html.EditorFor(Function(model) model.LastName, New With {Key .htmlAttributes = New With {Key .ng_model = "model.LastName"}})

但是当我在Views\Shared\EditorTemplates\Date.vbhtml中添加日期数据类型的自定义编辑器模板时,如下所示

@Code
    Dim value = ""
    If Not Model Is Nothing Then
        value = String.Format("{0:d}", Model.Value.ToString("dd/MM/yyyy"))
    End If
    @Html.TextBox("", value, New With {Key .class = "datefield", Key .type = "text"})
End Code

我使用带有htmlAttributes的EditorFor然后HtmlAttributes没有呈现?

1 个答案:

答案 0 :(得分:0)

这是我用于自定义DateTime编辑器模板的代码示例。我能够访问传递给editorfor的htmlattributes。希望这会有所帮助。

@model DateTime

@{
    object htmlAttributes = null;
    if (ViewContext.ViewData.Keys.Contains("htmlAttributes"))
    {
        htmlAttributes = ViewContext.ViewData["htmlAttributes"];
    }
}

@Html.TextBoxFor(model => model, htmlAttributes)