views:

42

answers:

3

I have this code in my view. I need to display the selected value that is comming from the database in the Dropdownlist.

<select id="PeopleClass" name="PeopleClass">
    <option value="1">Name1</option>
    <option value="2">Name2</option>
    <option value="3">Name3</option>
</select>

Now I am getting default as Name1 but what ever the database value I am coming I need to display in the view?

Can anybody help me out?

+1  A: 

Setting the selected attribute on the option that you want selected as default should do the trick.

Eg:

<select id="PeopleClass" name="PeopleClass">
    <option value="1">Name1</option>
    <option value="2">Name2</option>
    <option value="3" selected="true">Name3</option>
</select>
Dunderklumpen
I think this is a MVC problem instead of pure html problem
D.J
but its allways showitn name3 what if I get name2 or Name1 from databse?
kumar
+3  A: 

DropDownListFor is the method you can use: check this for more details: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor.aspx

I would suggest you Create

<select id="PeopleClass" name="PeopleClass">
    <option value="1">Name1</option>
    <option value="2">Name2</option>
    <option value="3">Name3</option>
</select>

into a IEnumerable<SelectListItem> and bind it when you render your view with your selected value from database.

// create People class
public class People{
     public value {get; set}
     public name {get; set}
}
//Create option list for your dropdown
List<People> peopleList= 
new List<People>{ new People{ value="1", name ="Name 1"}, new People{ value="2", name ="Name 2"}, new People{ value="3", name ="Name 3"}};
//bind it with ViewData
ViewData["ddl"] = new SelectList(peopleList, "value", "name", valueFromDatabase ); 

lastly in your view, bind the dropdown list with ViewData["ddl"]

<%=Html.DropDownListFor(model => model.People,(IEnumerable<SelectListItem>)ViewData["ddl"])%>
D.J
+1  A: 

In your code-behind you need to set the SelectedValue on the dropdownlist control.

Replace the code you pasted above with the following:

<asp:dropdownlist id=ddlPeopleClass runat=server>
 <asp:listitem value=1>Name1</asp:listitem>
 <asp:listitem value=2>Name2</asp:listitem>
 <asp:listitem value=3>Name3</asp:listitem>
</asp:dropdownlist>

As mentioned in a previous answer set the selected to true on the list item to select it.

 <asp:listitem value=3 selected=true>Name3</asp:listitem>

But as you've stated your value comes from the database so you'll be setting this in the code behind.

Naeem Sarfraz