Search code examples
c#asp.net-mvchtml.dropdownlistfor

@html.dropdownlistfor disable one item if condition


I am doing and MVC Application and I have a DropDownListFor and I need to Disable an Item depend on Condition..

Here is my DropDownList

 @Html.DropDownListFor(model => Model.SubsidyPlanType, new SelectList(new Dictionary<string, string> { { "", "" }, { "1", "Dollar" }, { "2", "Percentage" }, { "3", "Active" } }, "Key", "Value"), new { id = "Type", @class = "form-control form-select" })

I need Option 3 "Active" to be disable if condition Model.Value = "1"

How can I disable a single Item.?

Thanks


Solution

  • Try the following example to set Disabled property that indicates whether this SelectListItem is disabled:

    @Html.DropDownListFor(model => Model.SubsidyPlanType,
          new Dictionary<string, string> { { "", "" }, { "1", "Dollar" }, { "2", "Percentage" }, { "3", "Active" } }
          .Select(d =>
          {
              return new SelectListItem() { Disabled = (d.Key == "3"), Text = d.Value, Value = d.Key };
          }),
          new { id = "Type", @class = "form-control form-select" })