0

I am new to ASP.NET MVC. I have inherited a code base that I am trying to work with. I have a need to add some basic HTML attributes. Currently, in my .cshtml file, there is a block like this:

@Html.DropDown(model => model.SomeValue, Model.SomeList)

This references a function in Extensions.cs. This function looks like the following:

public static MvcHtmlString DropDown<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IEnumerable<string> items, string classes = "form-control")
{
  var attributes = new Dictionary<string, object>();
  attributes.Add("class", classes);

  return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(html, expression, itemList.Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }), null, attributes);
}

I now have a case where I need to disable the drop down in some scenarios. I need to evaluate the value of Model.IsUnknown (which is a bool) to determine whether or not the drop down list should be enabled or not.

My question is, how do I disable a drop down list if I need to? At this point, I do not know if I need to update my .cshtml or the extension method.

Thank you for any guidance you can provide.

1 Answer 1

6

Add an optional parameter in your extension method for disabling named enabledand bydefaut it will be true and from view pass bool parameter to disable or enable it:

public static MvcHtmlString DropDown<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IEnumerable<string> items, string classes = "form-control",bool enabled=true)
{
  var attributes = new Dictionary<string, object>();
  attributes.Add("class", classes);
  if(!enabled)
     attributes.Add("disabled","disabled");

  return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(html, expression, itemList.Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }), null, attributes);
}

and now in View:

@Html.DropDown(model => model.SomeValue, Model.SomeList,enabled:false)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.