I am having an issue with dropdowns and the viewbag. I am setting a dropdown using the following code in my controller:
applicationGuid = new Guid(form["applicationList"]);
var applications = _applicationRepository.List();
ViewBag.applicationList = new SelectList(applications, "Id", "Name", applicationGuid);
and in the view, this works perfectly and returns the previously selected value (applicationGuid):
@Html.DropDownList("applicationList", "")
Now I want to use the following code as I want to add some attributes to the dropdown:
@Html.DropDownList("applicationList", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" })
but for some reason, the selected value is not rendered (even though it is passed to the view and I can see selected = "true" against the correct item in the ViewBag SelectList).
The two examples above render as (this one has the selected="selected"):
<select id="applicationList" name="applicationList"><option value=""></option><option selected="selected" value="2f666645-9b28-406f-bd9f-9ecc009346a6">app1</option><option value="898cbbb5-5dff-4378-b15a-9ecc00b8242f">app2</option></select>
and like so (selected is gone!!):
<select class="required" id="applicationList" name="applicationList" rel="0"><option value=""></option><option value="2f666645-9b28-406f-bd9f-9ecc009346a6">app1</option><option value="898cbbb5-5dff-4378-b15a-9ecc00b8242f">app2</option></select>
Can anyone explain what I'm doing wrong here and why it is losing the selected value? I have found a number of posts that go into how the names of view data items cannot clash etc but I have stripped this right down with random names and nothing seems to work! Is this a problem in MVC3?
The problem seems to be that when you pass the SelectList
as a parameter to Html.DropDownList()
, it doesn't like it to have the same name as the actual dropdown list.
I copied your code and encountered the same problem as you.
But as soon as I changed
@Html.DropDownList("applicationList", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" })
to
@Html.DropDownList("applicationListX", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" })
It produced the working output:
<select class="required" id="applicationListX" name="applicationListX" rel="0"><option value=""></option>
<option selected="selected" value="2f666645-9b28-406f-bd9f-9ecc009346a6">app1</option>
<option value="898cbbb5-5dff-4378-b15a-9ecc00b8242f">app2</option>
</select>
I don't know why that's the case, but there's your workaround.
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