ASP.NET MVC中EditorFor()的Html属性

Typ*_*son 129 html asp.net-mvc editorfor

为什么我不能传入html属性EditorFor()?例如;

<%= Html.EditorFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", readonly = "readonly" }) %>
Run Code Online (Sandbox Code Playgroud)

我不想使用元数据

更新:解决方案是从视图中调用它:

 <%=Html.EditorFor( model => model.Control.PeriodEndDate, new {Modifiable=model.Control.PeriodEndDateModifiable})%>
Run Code Online (Sandbox Code Playgroud)

ViewData["Modifiable"]在我的自定义EditorTemplates/String.ascx中使用,其中我有一些视图逻辑,确定是否将readonly和/或disabled属性添加到输入传入的匿名对象EditorFor()是一个被调用的参数additionalViewData,其属性被传递给编辑器模板ViewData采集.

Ant*_*onK 115

更新 MVC 5.1现在直接支持以下方法,因此它也适用于内置编辑器.http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (这是一个伟大的思想相似的案例或他们阅读我的答案:)

结束更新

如果您使用自己的编辑器模板或MVC 5.1,现在支持以下方法直接用于内置编辑器.

@Html.EditorFor(modelItem => item.YourProperty, 
  new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px"  } })
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中(MVC 5.1中的简单类型不需要)

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])
Run Code Online (Sandbox Code Playgroud)

  • 这个新功能完美地解决了四年前提出的原始问题. (5认同)

Dar*_*rov 96

EditorFor使用元数据,所以如果你想添加html属性,你总是可以这样做.另一种选择是简单地编写自定义模板并使用TextBoxFor:

<%= Html.TextBoxFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", @readonly = "readonly" }) %>    
Run Code Online (Sandbox Code Playgroud)

  • 我现在找你 我可以使用<%= Html.EditorFor(model => model.Control.PeriodEndDate,new {Modifiable = model.Control.PeriodEndDateModifiable})%>并在我的自定义EditorTemplates/String.ascx中使用ViewData ["PeriodEndDateModifiable"].谢谢 (2认同)

小智 42

从MVC 5.1开始,您现在可以执行以下操作:

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })
Run Code Online (Sandbox Code Playgroud)

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features

  • 如何合并htmlAttributes? (2认同)

Mur*_*san 6

现在,ASP.Net MVC 5.1得到了内置的支持.

从发行说明

我们现在允许在EditorFor中传递HTML属性作为匿名对象.

例如:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 5

以下是MVC 5.1 EditorFor中 html 属性的VB.Net 代码语法

@Html.EditorFor(Function(x) x.myStringProp, New With {.htmlAttributes = New With {.class = "myCssClass", .maxlength="30"}}))
Run Code Online (Sandbox Code Playgroud)