ASP.NET MVC 3 Razor - Adding class to EditorFor

2020-01-25 04:25发布

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

This is not working:

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

16条回答
Luminary・发光体
2楼-- · 2020-01-25 04:34

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.

@Html.TextBoxFor(x => x.Created, new { @class = "date" }) 
查看更多
叛逆
3楼-- · 2020-01-25 04:37

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 UI drop-down calendar). In my research, the root issues I came across were:

  • The standard TextBoxFor helper 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 EditorFor would 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.

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

  • 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.

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-picker class decoration to then render the calendar, here it is:

$(document).ready(function () {
    $('.date-picker').datepicker({ inline: true, maxDate: 0, changeMonth: true, changeYear: true });
    $('.date-picker').datepicker('option', 'showAnim', 'slideDown');
});
查看更多
Juvenile、少年°
4楼-- · 2020-01-25 04:38

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

@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

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-01-25 04:42

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.

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...

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.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 RouteValueDictionary to parse the htmlAttributes passed in. I merge the attributes where they already exist, or add a new attribute if it does not yet exist.

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

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).

查看更多
6楼-- · 2020-01-25 04:43

You can create the same behavior creating a simple custom editor called DateTime.cshtml, saving it in Views/Shared/EditorTemplates

@model DateTime

@{
    var css = ViewData["class"] ?? "";
    @Html.TextBox("", (Model != DateTime.MinValue? Model.ToString("dd/MM/yyyy") : string.Empty), new { @class = "calendar medium " + css});
}

and in your views

@Html.EditorFor(model => model.StartDate, new { @class = "required" })

Note that in my example I'm hard-coding two css classes and the date format. You can, of course, change that. You also can do the same with others html attributes, like readonly, disabled, etc.

查看更多
7楼-- · 2020-01-25 04:45

There isn't any EditorFor override 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.

查看更多
登录 后发表回答