本文介绍了如何设置默认值从模型ASP.NET MVC的DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MVC新。所以我下拉列表填充这样
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>)
我想知道我怎么可以填充从模型下拉菜单,也可以设置默认值。任何样品code将是很大的帮助。谢谢
i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks
推荐答案
嗯,这是不这样做的好方法。
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.
public class MyViewModel{
public List<SelectListItem> CountryList {get; set}
public string Country {get; set}
public MyViewModel(){
CountryList = new List<SelectListItem>();
Country = "USA"; //default values go here
}
你需要的数据填充它。
Fill it with the data you need.
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
MyViewModel myViewModel = new MyViewModel ();
foreach(var item in countryQuery)
{
myViewModel.CountryList.Add(new SelectListItem() {
Text = item,
Value = item
});
}
myViewModel.Country = "UK";
//Pass it to the view using the `ActionResult`
return ActionResult( myViewModel);
}
目前来看,宣布这种观点是使用下面一行在文件的顶部期待着与类型MyViewModel模型
At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file
@model namespace.MyViewModel
和随时为你讨好你可以使用模型
And at anytime you may use the Model as you please
@Html.DropDownList("Country", Model.CountryList, Model.Country)
这篇关于如何设置默认值从模型ASP.NET MVC的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!