When using an HTML Helper, what is the best method to set an attribute based on a condition. For example
<%if (Page.User.IsInRole(\"administrator\")) {%&g
I could suggest you to use mvccontrib.FluentHtml.
You can do something like this
<%=this.TextBox(m=>m.FirstNam ).Disabled(Page.User.IsInRole("administrator"))%>
Created an extension method on Object that will create a copy of the input object excluding any properties that are null, and return it all as dictionary that makes it easily used in MVC HtmlHelpers:
public static Dictionary<string, object> StripAnonymousNulls(this object attributes)
{
var ret = new Dictionary<string, object>();
foreach (var prop in attributes.GetType().GetProperties())
{
var val = prop.GetValue(attributes, null);
if (val != null)
ret.Add(prop.Name, val);
}
return ret;
}
Not sure about performance implications of reflecting through properties twice, and don't like the name of the extension method much, but it seems to do the job well ...
new {
@class = "contactDetails",
disabled = Page.User.IsInRole("administrator") ? "true" : null
}.StripAnonymousNulls()
You'll need to pass a Dictionary<string, object>
, and add the disabled
key inside an if
statement.
I recommend making an overload of the extension method that takes a bool disabled
parameter and adds it to a RouteValueDictionary created from the attributes parameter if it's true
. (You could also remove the disabled
entry from the RouteValueDictionary
if it's false
, and not take another parameter)
You may want to consider writing your own HtmlHelper Extension class with a new TextBox method:
public static class HtmlHelperExtensions
{
public static MvcHtmlString TextBoxFor(this HtmlHelper htmlHelper, Expression<Func<TModel, TProperty>> expression, string cssClass, bool disabled)
{
return disabled
? Html.TextBoxFor(expression, new {@class=cssClass, disabled="disabled"})
: Html.TextBoxFor(expression, new {@class=cssClass})
}
}
now (if this new class is in the same namespace, or you've imported the new namespace to your page header, or in the pages section of the web.config) you can do this on your aspx page:
<%=Html.TextBoxFor(m => m.FirstName, "contactDetails", Page.User.IsInRole("administrator")) %>
You may also define this param that way:
Page.User.IsInRole("administrator")
? (object)new { @class='contactDetails'}
: (object)new { @class='contactDetails', disabled = true}
Page.User.IsInRole("administrator") ? null : new { disabled = "disabled" }