Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Html.DropDownList SelectedValue

Tags:

asp.net-mvc

I have tried this is RC1 and then upgraded to RC2 which did not resolve the issue.

// in my controller ViewData["UserId"] = new SelectList(     users,      "UserId",      "DisplayName",      selectedUserId.Value); // this has a value 

result: the SelectedValue property is set on the object

// in my view <%=Html.DropDownList("UserId", (SelectList)ViewData["UserId"])%> 

result: all expected options are rendered to the client, but the selected attribute is not set. The item in SelectedValue exists within the list, but the first item in the list is always defaulted to selected.

How should I be doing this?

Update Thanks to John Feminella's reply I found out what the issue is. "UserId" is a property in the Model my View is strongly typed to. When Html.DropDownList("UserId" is changed to any other name but "UserId", the selected value is rendered correctly.

This results in the value not being bound to the model though.

like image 380
blu Avatar asked Mar 09 '09 02:03

blu


People also ask

How get dropdown selected value from view to controller in MVC?

If you want to pass the selected value of your dropdown list into your controller, just add a string parameter with the name drpFields (same as the first parameter of your DropDownList method) into your temp action method.


2 Answers

This is how I fixed this problem:

I had the following:

Controller:

ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ; 

View

<%=Html.DropDownList("DealerTypes", ViewData["DealerTypes"] as SelectList)%> 

Changed by the following:

View

<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%> 

It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.

like image 60
Sanchitos Avatar answered Sep 19 '22 16:09

Sanchitos


Try this:

public class Person {     public int Id { get; set; }     public string Name { get; set; } } 

And then:

var list = new[] {        new Person { Id = 1, Name = "Name1" },      new Person { Id = 2, Name = "Name2" },      new Person { Id = 3, Name = "Name3" }  };  var selectList = new SelectList(list, "Id", "Name", 2); ViewData["People"] = selectList;  Html.DropDownList("PeopleClass", (SelectList)ViewData["People"]) 

With MVC RC2, I get:

<select id="PeopleClass" name="PeopleClass">     <option value="1">Name1</option>     <option selected="selected" value="2">Name2</option>     <option value="3">Name3</option> </select> 
like image 22
John Feminella Avatar answered Sep 16 '22 16:09

John Feminella