Get value of disabled dropdown in asp.net mvc

I have an ASP.NET MVC application. I have several drop-down lists on my page (HTML SELECT), I have to disable them, as the user continues to select them one at a time. When the user sends it back to the controller, I get null as a parameter to the function (action). I searched and found that HTML does not send the value of disabled fields to form data. Replacing a disabled attribute with readonly will not work, as this will lead to a drop down menu.

I generate dropdowns dynamically using javascript when the user continues to work. Thus, there is not a single drop-down list, but as much as the user wants.

Can someone tell me how to get the values?

+18
html post drop-down-menu asp.net-mvc
Jul 05 2018-12-19T00:
source share
4 answers

One of the possibilities is to create a disabled="disabled" drop-down list and include a hidden field with the same name and value that will allow this value to be sent to the server:

 @Html.DropDownListFor(x => x.FooId, Model.Foos, new { disabled = "disabled" }) @Html.HiddenFor(x => x.FooId) 

If you need to disable the drop-down list dynamically using javascript, simply assign the current selected value of the drop-down list to the hidden field immediately after it is disabled.

+39
Jul 05 2018-12-12T00:
source share

This is the default behavior for disabled controls. I suggest you add a hidden field and set the value of your DropDownList in this hidden field and work with it.

Something like:

 //just to create a interface for the user @Html.DropDownList("categoryDump", (SeectList)ViewBag.Categories, new { disabled = "disabled" }); // it will be send to the post action @Html.HiddenFor(x => x.CategoryID) 
+3
Jul 05 '12 at 19:55
source share

You can also create your own DropDownListFor overload, which accepts the bool disabled parameter and does a heavy lift for you so that your eyes are not cluttered with if disablethisfield then ...

Some of these lines could do:

 public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, bool disabled) { if (disabled) return MvcHtmlString.Create(htmlHelper.HiddenFor(expression).ToString() + htmlHelper.DropDownListFor(expression, selectList, new { disabled="disabled" }).ToString()); else return htmlHelper.DropDownListFor(expression, selectList); } 

There are 6 overloads for DropDownListFor alone, so this is a lot of monkeycoding, but it will pay off at the end of imho.

0
Nov 20 '12 at 15:51
source share

before sending a call to $ ('# FooId'). removeAttr ('disabled')

-2
Nov 11 '14 at 16:20
source share



All Articles