Search code examples
asp.netasp.net-mvcrazorasp.net-mvc-5.1editorfor

EditorFor extension not working for htmlAttributes in Asp.Net MVC 5.1


I have the following code:

public static class HtmlExtendedHelpers
{

    public static IHtmlString eSecretaryEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel,TProperty>> ex, object htmlAttributes, bool disabled )
    {

        if (disabled)
        {
            htmlAttributes.Add(new { @disabled = "disabled" }); //searching for working code as replacement for this line
        }

        return htmlHelper.EditorFor(ex, htmlAttributes);

    }
}

It works when disabled = false and all my alternatives fail when i disabled is true. Then none of the htmlAttributes are getten written.

The variable htmlAttribute has the VALUE ( including htmlAttributes property :)

htmlAttributes: { class = "form-control" }

This is because i have a default class of form-control and i want to add a attribute : disabled with value disabled.

Does anyone know how to implement this correctly?

PS. Since Asp.Net MVC 5.1, there is support for htmlAttributes


Solution

  • You can use HtmlHelper.AnonymousObjectToHtmlAttributes

    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    
    if (disabled)
    {
        attributes.Add("disabled", "disabled");
    }
    

    Alternatively, you could pass the disabled attribute as part of the htmlAttributes object, meaning you wouldn't need the if statement at all.

    htmlAttributes: { class = "form-control", disabled = "disabled" }
    

    Depending on whether you have a custom EditorFor template or not, you may need to change how you pass the html attributes to the EditorFor function, as the parameter it accepts - additionalViewData is not the same.

    This article explains in more detail.

    If you are using a default template, you can pass the html attributes inside another anonymous object:

    return htmlHelper.EditorFor(ex, new { htmlAttributes = attributes });
    

    If you have a custom template, you will need to retrieve the html attributes and apply them yourself in the view:

    @{
        var htmlAttributes = ViewData["htmlAttributes"] ?? new { };
    }