1. for example i have next helper and i need set status readonly (or disabled)
@Html.TextBoxFor(model => model.RequestTypeAdditional, new { @class = "form-control", @autocomplete = "off" , **readonly = IsReadOnly(Model.IsClosed)** })
@functions
{
private static string IsReadOnly( bool isClosed)
{
if (RoleHelpers.IsInRoles("Master"))
return "readonly";
else if (RoleHelpers.IsInRoles("Operator") && (!isClosed))
return string.Empty;
else if (RoleHelpers.IsInRoles("Operator") && (isClosed))
return "readonly";
else if (RoleHelpers.IsInRoles("Administrator"))
return string.Empty;
else
return "readonly";
}
}
2. i have custom view for model :-
@Html.DisplayFor(model => model.RequestType, new { **@readonly = IsReadOnly(Model.IsClosed)** })
works only if the readonly (or disabled) explicitly specified or not. custom helpers not suitable
Why can't you do this:
@if (IsReadOnly(Model.IsClosed))
{
@Html.TextBoxFor(model => model.RequestType, new { @readonly = "readonly" })
}
else
{
@Html.TextBoxFor(model => model.RequestType)
}
Do not try an brute force it. I agree you don't want your form code bloated with multiple repeating blocks.
I would recommend taking the code suggested by Sergey Shabanov
above and placing it into display template. Then use a UIHint
in our model to link to the display template. Presto, code complete with no bloat in your form code. You get to keep your DisplayFor
and generally it resolves to a single line of UI code. Finally, you keep the implementation in a single location so changing it is not as error prone.
I also think this could be one of the best ways to implement your strongly-typed TextBox custom helper:
public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>expression, bool isReadonly, bool isAutocomplete)
{
MvcHtmlString html = default(MvcHtmlString);
if (isReadonly)
{
html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "readOnly form-control", @autocomplete = isAutocomplete ? "on" : "off", @readonly = "read-only" });
}
else
{
html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "readOnly form-control", @autocomplete = isAutocomplete ? "on" : "off" });
}
return html;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.