I am trying to disable or enable a dropdownlistfor in my mvc application based on model property:-
what I am doing is :-
@Html.DropDownListFor(m => m.
It is not possible to include the condition (if/ternary statement(s)) inside the call to the DropDownListFor
helper method because you cannot pass a line of c# code (with your if condition) where it expects an object for html attributes. Also all of the below markups will render a disabled SELECT.
You can simply check the value of your Model property with an if condition and conditionally render the disabled version.
@if (!Model.IsReadOnly)
{
@Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"))
}
else
{
@Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"),new {disabled="disabled"})
}
You may consider creating a custom html helper method which takes care of the if condition checking.
public static class DropDownHelper
{
public static MvcHtmlString MyDropDownListFor
(this HtmlHelper htmlHelper,
Expression> expression,
IEnumerable selectItems,
object htmlAttributes,
bool isDisabled = false)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,
htmlHelper.ViewData);
IEnumerable items =
selectItems.Select(value => new SelectListItem
{
Text = value.Text,
Value = value.Value,
Selected = value.Equals(metadata.Model)
});
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (isDisabled && !attributes.ContainsKey("disabled"))
{
attributes.Add("disabled", "disabled");
}
return htmlHelper.DropDownListFor(expression,items, attributes);
}
}
Now in your razor view,call this helper
@Html.MyDropDownListFor(s=>s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name")
,new { @class="myClass"},Model.IsReadOnly)