i am new in mvc. so i populate dropdown this way
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
List<SelectListItem> countryList = new List<SelectListItem>();
string defaultCountry = "USA";
foreach(var item in countryQuery)
{
countryList.Add(new SelectListItem() {
Text = item,
Value = item,
Selected=(item == defaultCountry ? true : false) });
}
ViewBag.Country = countryList;
ViewBag.Country = "UK";
return View();
}
@Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)
i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks
If the
DropDownList
is filled in the controller and sent to the view viaViewBag
, you can do:You can't set the default value using
Html.DropDownList
, if you want to have a default value, the property itself should have a default value.Then, when the drop down list renders, as long as "UK" is actually a value for one of the options, it will be automatically set to that.
Well this is not a great way to do this.
Create a ViewModel that will hold everything you want to be rendered at the view.
Fill it with the data you need.
At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file
And at anytime you may use the Model as you please