how to display selected value in drop down list in asp.net mvc?
i want to display selected value in drop down list . the value comes from the data base. for ex suppose we want to update user profile then value for gender which is previously provided by the user should get displayed a开发者_开发技巧s selected value. the code that i used to display is
<% string val = Convert.ToString(Model.gender);
ViewData["gen"] = val;
%>
<%= Html.DropDownList("genderList", ViewData["gen"] as SelectList) %>
but its not showing the value from the database.but viewdata get value from database but it is not showing on drop down list. thanks in advance.
You can check this blog post which shows how to use a DropDownList in ASP.NET MVC.
This:
string val = Convert.ToString(Model.gender);
ViewData["gen"] = val;
is not compatible with this:
ViewData["gen"] as SelectList
ViewData["gen"]
contains a string value instead of SelectList
and when you try to cast it you get null and the drop down contains no values.
You will need an array in order to populate the drop down list. The first step is to have a strongly typed array of some object. Suppose that you have the following class defined:
public class Gender
{
public int Id { get; set; }
public int Text { get; set; }
}
In your controller action:
public ActionResult Index()
{
var genderList = new[]
{
new Gender{ Id = 1, Text = "Male" },
new Gender{ Id = 2, Text = "Female" },
}; // This should come from the database
ViewData["genderList"] = new SelectList(genderList, "Id", "Text");
return View();
}
and in the view:
<%= Html.DropDownList("gen", ViewData["genderList"] as SelectList) %>
精彩评论