Reputation: 3528
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
Upvotes: 3
Views: 2010
Reputation: 1041
You can pass the attributes in the htmlAttributes like below:
htmlAttributes: { class = "form-control", disbaled="disabled" }
Also you can create your Metadata Attribute which can be decorated on your property for which you are using EditorFor.
To create your own Metadata Property you can implement IMetadataAware
interface.
Upvotes: 0
Reputation: 4320
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 { };
}
Upvotes: 5