asp.net-mvc – 如何从模型中为ASP.NET MVC DropDownList设置默
发布时间:2020-12-16 07:19:50 所属栏目:asp.Net 来源:网络整理
导读:我是mvc的新手.所以我用这种方式填充下拉列表 public ActionResult New(){ var countryQuery = (from c in db.Customers orderby c.Country ascending select c.Country).Distinct(); ListSelectListItem countryList = new ListSelectListItem(); string de
我是mvc的新手.所以我用这种方式填充下拉列表
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>) 我想知道如何从模型填充下拉列表并设置默认值.任何示例代码都会有很大的帮助.谢谢 解决方法
那么这不是一个很好的方法.
创建一个ViewModel,它将保存您想要在视图中呈现的所有内容. 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 } 填写您需要的数据. 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类型的Model使用文件顶部的以下行 @model namespace.MyViewModel 您可以随时使用该模型 @Html.DropDownList("Country",Model.CountryList,Model.Country) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 使用ASP.net和Access数据库保护SQL Injection的网站
- asp.net-core – 使用NLog记录请求正文和请求标头
- 处理global.asax ASP.NET MVC中的异常
- asp.net – 如何创建自定义数据注释验证器
- asp.net-mvc – ASP.NET MVC Html.RadioButton异常
- asp.net-mvc-3 – Webgrid MVC 3条件行样式
- ASP.NET中模式弹出窗口的最佳选择?
- [你必须知道的.NET] 开篇有益
- asp.net-mvc-3 – 如果在Razor中的else语句不起作用
- asp.net-mvc – 如何将整数列表传递给MVC操作?
推荐文章
站长推荐
- asp.net-mvc – 在哪里进行审计或记录?
- asp.net – 使用IIS7应用程序请求路由修改标头
- .NET Core的日志[3]:将日志写入Debug窗口
- asp.net-mvc – Json返回时如何读取modelstate错
- asp.net-mvc – 在Html.ActionLink(MVC 4)中使用
- asp.net-mvc-3 – 如何在asp.net mvc3中将Id从父
- [你必须知道的.NET] 第一回:恩怨情仇:is和as
- asp.net-mvc – 使用401发送消息:Asp.net Web-a
- asp.net – 仅为某些路径设置RAMMFAR
- asp.net-mvc – 哪里可以将商业模式转换成模型?
热点阅读