Setting default value to Html.DropDownListFor

╄→尐↘猪︶ㄣ 提交于 2019-12-11 03:49:07

问题


I am populating a dropdownlist in mvc using viewbag. i want to set a default value to this dropdownlist, if the page is not saved with any other value. Otherwise the selected item should be the one they select and save the page.

this is how i populate my viewbag

ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");

this is the view side:

<%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>

回答1:


If you want to pass default value for the dropdown list than you can do is pass default viewmodel/model with default value

Example :

public ActionResult New()
{
    MyViewModel myViewModel = new MyViewModel ();
    myViewModel.OfficeAddressCountry = default value; 
    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

or you can try this

 var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
 list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
 ViewBag.ListOfCountries = list;



回答2:


You have to use different overlaod of DropDownListFor. Consider this:

<%: Html.DropDownListFor(m => m.OfficeAddressCountry,
                         ViewBag.ListOfCountries as SelectList,
                         "Default Selected Option",
                         new{@class="required"}) %>

Now it will set default selected option to "Default Selected Option" if the model property OfficeAddressCountry contains no value.

You can check this fiddle for default value and this with selected option which is in Model




回答3:


<%: Html.DropDownListFor(m => m.OfficeAddressCountry,
                     ViewBag.ListOfCountries as SelectList,
                     "Default Selected Option",
                     new{@class="required"}) %>


来源:https://stackoverflow.com/questions/31261389/setting-default-value-to-html-dropdownlistfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!