ASP.NET MVC 3 Razor - Adding class to EditorFor

后端 未结 16 2052
长情又很酷
长情又很酷 2020-11-27 11:09

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

This is not working:

@Html.EditorFor(x => x.Created, new { @class = \"date\" })
16条回答
  •  春和景丽
    2020-11-27 11:33

    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(this HtmlHelper htmlHelper, Expression> 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');
    });
    

提交回复
热议问题