I have an ASP.NET MVC application. I am having multiple drop-down list in my page (HTML SELECT), I have to disable them, as user goes on selected them one by one. When the user posts it back to the controller, I am getting null as the function (action method) paramters. I searched and found that HTML does not send value of disabled fields in the form data. Replacing disabled attribute with readonly would not work as it would render drop-down working.
I am generating the dropdowns dynamically using javascript as user goes on. So there isn't a single dropdown, but as many as user wants.
Can someone please tell me how should I get the values ?
One possibility is to make the dropdown list disabled="disabled"
and include a hidden field with the same name and value which will allow to send this value to the server:
@Html.DropDownListFor(x => x.FooId, Model.Foos, new { disabled = "disabled" })
@Html.HiddenFor(x => x.FooId)
If you have to disabled the dropdown dynamically with javascript then simply assign the currently selected value of the dropdown to the hidden field just after disabling it.
This is the default behavior of disabled controls. I suggest you to add a hidden field and set the value of your DropDownList in this hidden field and work with this.
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)
You could also create your own DropDownListFor overload which accepts a bool disabled
parameter and does the heavy lifting for you so your view isn't cluttered with if disablethisfield then ...
.
Something among 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 it's a lot of monkeycoding but it pays off in the end imho.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With