MVC 3 Dropdown plays selected value using ViewBag

I have a problem with dropdowns and viewbag. I set the dropdown using the following code in the controller:

        applicationGuid = new Guid(form["applicationList"]);

        var applications = _applicationRepository.List();

        ViewBag.applicationList = new SelectList(applications, "Id", "Name", applicationGuid);

and in the view, this works fine and returns the previously selected value (applicationGuid):

 @Html.DropDownList("applicationList", "")

Now I want to use the following code, because I want to add some attributes to the drop-down list:

 @Html.DropDownList("applicationList", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" }) 

but for some reason, the selected value is not displayed (even if it is passed to the view, and I see the selected value = "true" against the correct item in the ListBag SelectList).

The two examples above display how (this 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 so (the chosen one has left !!):

<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> 

- , ? , , .., ! MVC3?

+5
1

, SelectList Html.DropDownList(), , , .

, .

@Html.DropDownList("applicationList", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" })

@Html.DropDownList("applicationListX", ViewBag.applicationList as SelectList, "", new { rel = "0", @class = "required" })

:

<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>

, , .

+14

All Articles