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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3735400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:31:53  来源:igfitidea点击:

Html attributes for EditorFor() in ASP.NET MVC

htmlasp.net-mvceditorfor

提问by Typo Johnson

Why can't I pass in html attributes to EditorFor()? eg;

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

<%= Html.EditorFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", readonly = "readonly" }) %>

I don't want to use metadata

我不想使用元数据

Update: The solution was to call this from the view :

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

 <%=Html.EditorFor( model => model.Control.PeriodEndDate, new {Modifiable=model.Control.PeriodEndDateModifiable})%>

and use ViewData["Modifiable"]in my custom EditorTemplates/String.ascx where I have some view logic that determines whether to add readonly and/or disabled attributes to the input The anonymous object passed into EditorFor()is a parameter called additionalViewDataand its properties are passed to the editor template in the ViewDatacollection.

ViewData["Modifiable"]在我的自定义 EditorTemplates/String.ascx 中使用,其中我有一些视图逻辑,用于确定是否向输入添加只读和/或禁用属性 传入的匿名对象EditorFor()是一个调用的参数additionalViewData,其属性被传递到ViewData收藏。

采纳答案by Darin Dimitrov

EditorForworks with metadata, so if you want to add html attributes you could always do it. Another option is to simply write a custom template and use TextBoxFor:

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

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

回答by AntonK

UpdateMVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features(It's either a case of Great mind thinking alike or they read my answer :)

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

End Update

结束更新

If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.

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

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

then in your template (not required for simple types in MVC 5.1)

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

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])

回答by vtforester

As of MVC 5.1, you can now do the following:

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

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })

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

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

回答by Murali Murugesan

Now ASP.Net MVC 5.1got a built in support for it.

现在ASP.Net MVC 5.1获得了对它的内置支持。

From Release Notes

来自发行说明

We now allow passing in HTML attributes in EditorFor as an anonymous object.

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

For example:

例如:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })

回答by Max

Here is the VB.Net codesyntax for html attributes in MVC 5.1EditorFor

这是MVC 5.1EditorFor中html属性VB.Net代码语法

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

回答by Mhoque

Why not just use

为什么不直接使用

@Html.DisplayFor(model => model.Control.PeriodType)

回答by John Farrell

If you don't want to use Metadata you can use a [UIHint("PeriodType")]attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.

如果你不想使用元数据,你可以使用[UIHint("PeriodType")]属性来装饰属性,或者如果它是一个复杂的类型,你不必装饰任何东西。EditorFor 然后将在 EditorTemplates 文件夹中查找 PeriodType.aspx 或 ascx 文件并使用它。

回答by Isochronous

I've been wrestling with the same issue today for a checkbox that binds to a nullable bool, and since I can't change my model (not my code) I had to come up with a better way of handling this. It's a bit brute force, but it should work for 99% of cases I might encounter. You'd obviously have to do some manual population of valid attributes for each input type, but I think I've gotten all of them for checkbox.

我今天一直在为绑定到可为空 bool 的复选框解决同样的问题,由于我无法更改我的模型(不是我的代码),我不得不想出更好的方法来处理这个问题。这有点蛮力,但它应该适用于我可能遇到的 99% 的情况。您显然必须为每种输入类型手动填充一些有效属性,但我想我已经为复选框获取了所有这些属性。

In my Boolean.cshtml editor template:

在我的 Boolean.cshtml 编辑器模板中:

@model bool?

@{
    var attribs = new Dictionary<string, object>();
    var validAttribs = new string[] {"style", "class", "checked", "@class",
        "classname","id", "required", "value", "disabled", "readonly", 
        "accesskey", "lang", "tabindex", "title", "onblur", "onfocus", 
        "onclick", "onchange", "ondblclick", "onmousedown", "onmousemove", 
        "onmouseout", "onmouseover", "onmouseup", "onselect"};
    foreach (var item in ViewData) 
    {
        if (item.Key.ToLower().IndexOf("data_") == 0 || item.Key.ToLower().IndexOf("aria_") == 0) 
        {
            attribs.Add(item.Key.Replace('_', '-'), item.Value);
        } 
        else 
        {
            if (validAttribs.Contains(item.Key.ToLower()))
            {
                attribs.Add(item.Key, item.Value);
            }
        }
    }
}

@Html.CheckBox("", Model.GetValueOrDefault(), attribs)

回答by Isochronous

You can still use EditorFor. Just pass the style/whichever html attribute as ViewData.

您仍然可以使用 EditorFor。只需将样式/任何 html 属性作为 ViewData 传递即可。

@Html.EditorFor(model => model.YourProperty, new { style = "Width:50px" })

Because EditorFor uses templates to render, you could override the default template for your property and simply pass the style attribute as ViewData.

因为 EditorFor 使用模板来呈现,所以您可以覆盖您的属性的默认模板,并简单地将 style 属性作为 ViewData 传递。

So your EditorTemplate would like the following:

因此,您的 EditorTemplate 需要以下内容:

@inherits System.Web.Mvc.WebViewPage<object>

@Html.TextBoxFor(m => m, new { @class = "text ui-widget-content", style=ViewData["style"] })

回答by xr280xr

In my case I was trying to create an HTML5 number input editor template that could receive additional attributes. A neater approach would be to write your own HTML Helper, but since I already had my .ascx template, I went with this approach:

就我而言,我试图创建一个可以接收附加属性的 HTML5 数字输入编辑器模板。一种更简洁的方法是编写自己的 HTML Helper,但由于我已经有了 .ascx 模板,所以我采用了这种方法:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<input id="<%= Regex.Replace(ViewData.TemplateInfo.GetFullHtmlFieldId(""), @"[\[\]]", "_") %>" name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>" type="number" value="<%= ViewData.TemplateInfo.FormattedModelValue %>"
<% if (ViewData["attributes"] != null)
   {
       Dictionary<string, string> attributes = (Dictionary<string, string>)ViewData["attributes"];
       foreach (string attributeName in attributes.Keys){%>
        <%= String.Format(" {0}=\"{1}\"", attributeName, attributes[attributeName])%>
       <% }
   } %> />

This ugly bit creates a number type input and looks for a ViewData Dictionary with the key "attributes". It will iterate through the dictionary adding its key/value pairs as attributes. The Regex in the ID attribute is unrelated and is there because when used in a collection, GetFullHtmlFieldId()returns an id containing square brackets []which it would normally escape as underscores.

这个丑陋的位创建了一个数字类型的输入,并使用键“属性”查找 ViewData 字典。它将遍历字典添加其键/值对作为属性。ID 属性中的正则表达式是不相关的,因为当在集合中使用时,它GetFullHtmlFieldId()返回一个包含方括号的 id [],它通常会作为下划线转义。

This template is then called like this:

这个模板然后像这样调用:

Html.EditorFor(m => m.Quantity, "NumberField", new { attributes = new Dictionary<string, string>() { { "class", "txtQuantity" } } }

Verbose, but it works. You could probably use reflection in the template to use property names as attribute names instead of using a dictionary.

冗长,但它的工作原理。您可能可以在模板中使用反射来使用属性名称作为属性名称,而不是使用字典。