Disable enable dropdownlistfor based on model property in mvc

前端 未结 3 1453
醉梦人生
醉梦人生 2021-01-27 16:23

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.         


        
3条回答
  •  悲哀的现实
    2021-01-27 17:11

    The accepted answer from Shyju works great. But what if you want to use HTML5 data-* attributes in your custom helper? The standard MVC DropDownListFor provides a workaround by using an underscore (_) in place of the dash (-). And that helper is intelligent enough to convert the underscores to dashes when the markup is rendered.

    Here is a custom helper that will provide a parameter to disable a DropDownList and also converts the HTML5 data-* attributes appropriately. It also preserves any other values passed in via the htmlAttributes parameter. The code is a little more concise as well (imo).

        public static MvcHtmlString MyDropDownListFor(this HtmlHelper htmlHelper, Expression> expression, IEnumerable list, string optionLabel, object htmlAttributes, bool disabled)
        {
            var routeValues = new System.Web.Routing.RouteValueDictionary();
    
            // convert underscores to dashes...
            foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes))
            {
                routeValues.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
            }
    
            if(disabled)
            {
                routeValues.Add("disabled", "disabled");
            }
    
            return htmlHelper.DropDownListFor(expression, list, optionLabel, routeValues);
        }
    

    And the markup:

    @Html.MyDropDownListFor(m => m.MonthId, Model.Months, "Select Month", new { @class = "form-control", data_url = Url.Action("GetMonths") }, Model.IsDisabled)

提交回复
热议问题