asp.net-mvc ASP.NET MVC 3 Razor - 向 EditorFor 添加类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4576209/
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-09-08 00:40:37  来源:igfitidea点击:

ASP.NET MVC 3 Razor - Adding class to EditorFor

asp.net-mvcasp.net-mvc-3razor

提问by user137348

I'm trying to add a class to an input.

我正在尝试向输入添加一个类。

This is not working:

这不起作用:

@Html.EditorFor(x => x.Created, new { @class = "date" })

采纳答案by Darin Dimitrov

Adding a class to Html.EditorFordoesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

添加一个类Html.EditorFor没有意义,因为在它的模板中你可以有许多不同的标签。所以你需要在编辑器模板中分配类:

@Html.EditorFor(x => x.Created)

and in the custom template:

并在自定义模板中:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>

回答by EF0

As of ASP.NET MVC 5.1, adding a class to an EditorForis possible (the original question specified ASP.NET MVC 3, and the accepted answer is still the best with that considered).

从 ASP.NET MVC 5.1 开始,向 an 添加类EditorFor是可能的(原始问题指定了 ASP.NET MVC 3,并且接受的答案仍然是最好的考虑)。

@Html.EditorFor(x=> x.MyProperty,
    new { htmlAttributes = new { @class = "MyCssClass" } })

See: What's New in ASP.NET MVC 5.1, Bootstrap support for editor templates

请参阅:ASP.NET MVC 5.1 中的新增功能,对编辑器模板的 Bootstrap 支持

回答by TuomasK

You can't set class for the generic EditorFor. If you know the editor that you want, you can use it straight away, there you can set the class. You don't need to build any custom templates.

您不能为通用 EditorFor 设置类。如果你知道你想要的编辑器,你可以马上使用它,你可以在那里设置类。您不需要构建任何自定义模板。

@Html.TextBoxFor(x => x.Created, new { @class = "date" }) 

回答by przno

You can use:

您可以使用:

@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })

(At least with ASP.NET MVC 5, but I do not know how that was with ASP.NET MVC 3.)

(至少对于 ASP.NET MVC 5,但我不知道 ASP.NET MVC 3 的情况如何。)

回答by bigmac

I had the same frustrating issue, and I didn't want to create an EditorTemplate that applied to all DateTime values (there were times in my UI where I wanted to display the time and not a jQuery UIdrop-down calendar). In my research, the root issues I came across were:

我遇到了同样令人沮丧的问题,我不想创建一个适用于所有 DateTime 值的 EditorTemplate(有时我想在我的 UI 中显示时间而不是jQuery UI下拉日历)。在我的研究中,我遇到的根本问题是:

  • The standard TextBoxForhelper allowed me to apply a custom class of "date-picker" to render the unobtrusive jQuery UI calender, but TextBoxFor wouldn't format a DateTime without the time, therefore causing the calendar rendering to fail.
  • The standard EditorForwould display the DateTime as a formatted string (when decorated with the proper attributes such as [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")], but it wouldn't allow me to apply the custom "date-picker" class.
  • 标准TextBoxFor助手允许我应用“日期选择器”的自定义类来呈现不显眼的 jQuery UI 日历,但 TextBoxFor 不会在没有时间的情况下格式化 DateTime,因此导致日历呈现失败。
  • 标准EditorFor会将 DateTime 显示为格式化字符串(当使用适当的属性装饰时,例如[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")],但它不允许我应用自定义的“日期选择器”类。

Therefore, I created custom HtmlHelper class that has the following benefits:

因此,我创建了具有以下优点的自定义 HtmlHelper 类:

  • The method automatically converts the DateTime into the ShortDateString needed by the jQuery calendar (jQuery will fail if the time is present).
  • By default, the helper will apply the required htmlAttributes to display a jQuery calendar, but they can be overridden if needs be.
  • If the date is null, ASP.NET MVC will put a date of 1/1/0001 as a value.
  • 该方法会自动将 DateTime 转换为 jQuery 日历所需的 ShortDateString(如果时间存在,jQuery 将失败)。
  • 默认情况下,助手将应用所需的 htmlAttributes 来显示 jQuery 日历,但如果需要,它们可以被覆盖。
  • 如果日期为空,ASP.NET MVC 会将日期 1/1/0001 作为值。

This method replaces that with an empty string.

此方法将其替换为空字符串。

public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
    var mvcHtmlString = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, htmlAttributes ?? new { @class = "text-box single-line date-picker" });
    var xDoc = XDocument.Parse(mvcHtmlString.ToHtmlString());
    var xElement = xDoc.Element("input");
    if (xElement != null)
    {
        var valueAttribute = xElement.Attribute("value");
        if (valueAttribute != null)
        {
            valueAttribute.Value = DateTime.Parse(valueAttribute.Value).ToShortDateString();
            if (valueAttribute.Value == "1/1/0001")
                valueAttribute.Value = string.Empty;
        }
    }
    return new MvcHtmlString(xDoc.ToString());
}

And for those that want to know the JQuery syntax that looks for objects with the date-pickerclass decoration to then render the calendar, here it is:

对于那些想要了解 JQuery 语法的人来说,该语法查找具有date-picker类装饰的对象然后呈现日历,这里是:

$(document).ready(function () {
    $('.date-picker').datepicker({ inline: true, maxDate: 0, changeMonth: true, changeYear: true });
    $('.date-picker').datepicker('option', 'showAnim', 'slideDown');
});

回答by Brett

It is possible to provide a class or other information through AdditionalViewData - I use this where I'm allowing a user to create a form based on database fields (propertyName, editorType, and editorClass).

可以通过 AdditionalViewData 提供类或其他信息 - 我使用它来允许用户基于数据库字段(propertyName、editorType 和 editorClass)创建表单。

Based on your initial example:

根据您的初始示例:

@Html.EditorFor(x => x.Created, new { cssClass = "date" })

and in the custom template:

并在自定义模板中:

<div>
    @Html.TextBoxFor(x => x.Created, new { @class = ViewData["cssClass"] })
</div>

回答by marcind

There isn't any EditorForoverride that lets you pass in an anonymous object whose properties would somehow get added as attributes on some tag, especially for the built-in editor templates. You would need to write your own custom editor template and pass the value you want as additional viewdata.

没有任何EditorFor覆盖可以让您传入匿名对象,该对象的属性会以某种方式添加为某些标签的属性,尤其是对于内置编辑器模板。您需要编写自己的自定义编辑器模板并将所需的值作为附加视图数据传递。

回答by Jayant Varshney

@Html.EditorFor(m=>m.Created ...) 

does not allow any arguments to be passed in for the Text box

不允许为文本框传递任何参数

This is how you can apply attributes.

这是您可以应用属性的方式。

@Html.TextBoxFor(m=>m.Created, new { @class= "date", Name ="myName", id="myId" })

回答by Praveen M P

Using jQuery, you can do it easily:

使用 jQuery,您可以轻松完成:

$("input").addClass("class-name")

Here is your input tag

这是您的输入标签

@Html.EditorFor(model => model.Name)

For DropDownlist you can use this one:

对于 DropDownlist,您可以使用这个:

$("select").addClass("class-name")

For Dropdownlist:

对于下拉列表:

@Html.DropDownlistFor(model=>model.Name)

回答by barrypicker

While the question was targeted at MVC 3.0, we find the problem persists in MVC 4.0 as well. MVC 5.0 now includes natively an overload for htmlAttributes.

虽然该问题针对 MVC 3.0,但我们发现该问题在 MVC 4.0 中也仍然存在。MVC 5.0 现在原生包含 htmlAttributes 的重载。

I am forced to use MVC 4.0 at my current place of employment and needed to add a css class for JQuery integration. I solved this problem using a single extension method...

我被迫在我目前的工作地点使用 MVC 4.0,并且需要为 JQuery 集成添加一个 css 类。我使用单一的扩展方法解决了这个问题......

Extension Method:

扩展方法:

using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;

namespace MyTest.Utilities
{
    public static class MVCHelperExtensionMethods
    {
        public static MvcHtmlString AddHtmlAttributes(this MvcHtmlString input, object htmlAttributes)
        {
            // WE WANT TO INJECT INTO AN EXISTING ELEMENT.  IF THE ATTRIBUTE ALREADY EXISTS, ADD TO IT, OTHERWISE
            // CREATE THE ATTRIBUTE WITH DATA VALUES.

            // USE XML PARSER TO PARSE HTML ELEMENT
            var xdoc = XDocument.Parse(input.ToHtmlString());
            var rootElement = (from e in xdoc.Elements() select e).FirstOrDefault();

            // IF WE CANNOT PARSE THE INPUT USING XDocument THEN RETURN THE ORIGINAL UNMODIFIED.
            if (rootElement == null)
            {
                return input;
            }

            // USE RouteValueDictionary TO PARSE THE NEW HTML ATTRIBUTES
            var routeValueDictionary = new RouteValueDictionary(htmlAttributes);

            foreach (var routeValue in routeValueDictionary)
            {
                var attribute = rootElement.Attribute(routeValue.Key);

                if (attribute == null)
                {
                    attribute = new XAttribute(name: routeValue.Key, value: routeValue.Value);
                    rootElement.Add(attribute);
                }
                else
                {
                    attribute.Value = string.Format("{0} {1}", attribute.Value, routeValue.Value).Trim();
                }
            }

            var elementString = rootElement.ToString();
            var response = new MvcHtmlString(elementString);
            return response;
        }
    }
}

HTML Markup Usage:

HTML 标记用法:

@Html.EditorFor(expression: x => x.MyTestProperty).AddHtmlAttributes(new { @class = "form-control" })

(Make sure to include the extension method's namespace in the razor view)

(确保在剃刀视图中包含扩展方法的命名空间)

Explanation:The idea is to inject into the existing HTML. I opted to parse the current element using Linq-to-XML using XDocument.Parse(). I pass the htmlAttributes as type object. I utilize MVC RouteValueDictionaryto parse the htmlAttributes passed in. I merge the attributes where they already exist, or add a new attribute if it does not yet exist.

说明:这个想法是注入到现有的 HTML 中。我选择使用 Linq-to-XML 解析当前元素XDocument.Parse()。我将 htmlAttributes 作为 type 传递object。我利用 MVCRouteValueDictionary来解析传入的 htmlAttributes。我合并它们已经存在的属性,或者如果它不存在就添加一个新属性。

In the event the input is not parsable by XDocument.Parse()I abandon all hope and return the original input string.

如果输入无法解析,XDocument.Parse()我放弃所有希望并返回原始输入字符串。

Now I can use the benefit of the DisplayFor (rendering datatypes such as currency appropriately) but also have the ability to specify css classes (and any other attribute for that matter). Could be helpful for adding attributes such as data-*, or ng-*(Angular).

现在我可以利用 DisplayFor 的好处(适当地呈现数据类型,例如货币),而且还可以指定 css 类(以及与此相关的任何其他属性)。可能有助于添加data-*, 或ng-*(Angular)等属性。