I need to select the dropdown in html helper. I pass my data in IEnumerable using ViewData please some one help me how to select it with value.
My Code is
If your ViewData["Brand"]
contains an object IEnumerable
, I guess you have already used its constructor or more likely Object Initializer, e.g.:
List brand = new List()
{
new { Value = 1 , Text = "something 1" },
new { Value = 2 , Text = "something 2" },
new { Value = 3 , Text = "something 3" },
};
ViewData["Brand"] = brand;
In your View, you use the list as a second parameter for DropDownList
helper. You also need to provide what its Value and Text. The last parameter indicates which value is to be selected by default:
@Html.DopDownList("Brand",
(List)ViewData["Brand"],
"value", "text", 2)
You could also try SelectList
container to "fill" the DropDownList
helper. Simply send your list of Objects to view in ViewData etc., and use it as a second parameter. Then provide Value and Text as the third and the fourth parameters, respectively. The last parameter corresponds to the value of your selected item in the list.
@Html.DropDownList("Brand", new SelectList(
Model.ListOfYourObjects,
"<<< Property name as value in the Object, e.g. ID",
"<<< Property name as text in the Object, e.g. Name/Title/etc.",
<<< value of thecurrent ID >>>));
e.g.
public class City
{
public int ID { get; set; }
public string Name { get; set; }
}
Then
ViewData["Cities"] = dbContext.Cities.ToList();
//or
ViewData["Cities"] = new List(); // fill this list
In a view:
@model List
// ...
@Html.DropDownList(
"Brand",
new SelectList(
Model, "ID", "Name",
<<< value of ID to be selected or null>>>
)
);
ID
and Name
are property names in the class City
which is important here in order for SelectList
to work.
I couldn't try this code but this should give you something to work with. Hope it can help.