我正在使用 viewbag 在 mvc 中填充下拉列表。 如果页面未使用任何其他值保存,我想为此下拉列表设置一个默认值。 否则所选项目应该是他们选择并保存页面的项目。
这就是我填充我的 viewbag 的方式
ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");
这是 View :
<%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>
最佳答案
如果你想为下拉列表传递默认值,你可以做的是用默认值传递默认 View 模型/模型
示例:
public ActionResult New()
{
MyViewModel myViewModel = new MyViewModel ();
myViewModel.OfficeAddressCountry = default value;
//Pass it to the view using the `ActionResult`
return ActionResult( myViewModel);
}
或者你可以试试这个
var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
ViewBag.ListOfCountries = list;
关于c# - 将默认值设置为 Html.DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31261389/