将列表绑定到MVC中的Dropdown [英] Bind list into Dropdown in MVC
本文介绍了将列表绑定到MVC中的Dropdown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的控制器代码:
my controller code:
var clentddl= db.ClientDetails.Where(x=>x.IsActive==true).Select(x=>x.Name).ToList();
ViewBag.Clientname = clentddl.ToList();
return View();
我的观点是:
my view is:
@Html.DropDownListFor(x => x.Clientname , ViewBag.Clientname as List<SelectListItem>, "PleaseSelect", new { @class = "form-control" })
问题:
i将数据放入列表并收集在viewbag中。如何在视图中绑定?
Problem:
i got the data into the list and collected in viewbag. how to bind in view??
推荐答案
使用下面的代码:
@ Html.DropDownListFor(model => model.ClientId,new SelectList(ViewBag.Clientname as System.Collections.IEnumerable,ClientId,RoleName),new {id =ddlClientName})
Use below code:
@Html.DropDownListFor(model => model.ClientId, new SelectList(ViewBag.Clientname as System.Collections.IEnumerable, "ClientId","RoleName"), new { id = "ddlClientName" })
1 。在ASP.NET MVC中,必须在视图
中使用的所有数据都应作为已使用的模型中的属性存在
。因此,在您的情况下,您必须扩展您的模型类,并在其中添加一个将用于此下拉列表的属性,然后您可以使用@ Html.DropDownListFor()在视图中使用它
并且不使用缓存到ViewBag中的数据。
2.要修复现有代码,必须在View <$ c中缓存$ c> 包含列表< SelectListItem>
的列表,而不是像现在这样的简单列表,所以在你的控制器中你必须建立此列表之前将其缓存到视图包中。
1.In ASP.NET MVC, all data that have to be used in theview
should exist as properties in the usedmodel
. So in your case you have to extends your model class and and into it a property that will be used for this drop down list, then you will can use it in the view by using@Html.DropDownListFor()
and not to use data cached into the ViewBag.
2.To fix your existing code you have to cache in the ViewBag a list of
List<SelectListItem>
and not a simple list like you are doing now, so in you controller you have to built this list before to cache it into the view bag.
这篇关于将列表绑定到MVC中的Dropdown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文