如何填充从数据库中dropdownlistfor在ASP.NET MVC 4 [英] How to populate an dropdownlistfor from database in ASP.NET MVC 4
问题描述
正如标题所说,我希望在这个任务一定的帮助,我读过很多关于它的教程,但没有人能解决我的问题是如何加载 dropdownlistfor
从数据库。到目前为止,我得到了以下code:
As the title says I'm looking for some help in that task, I've read many tutorials about it but none of them can solved my problem which is how to load a dropdownlistfor
from database. By far, I got the following code:
**LNClientes():**
public List<ENDistrito> DistritoListar()
{
return new ADClientes().DistritoListar();
}
**ADClientes():**
public List<ENDistrito> DistritoListar()
{
Database oDatabase = DatabaseFactory.CreateDatabase(ConfigurationManager.AppSettings["conexionBD"]);
DbCommand odbcommand = oDatabase.GetStoredProcCommand("USP_SEL_DISTRITOS");
List<ENDistrito> lista = new List<ENDistrito>();
using (IDataReader reader = oDatabase.ExecuteReader(odbcommand))
{
while (reader.Read())
lista.Add(new ENDistrito(reader));
}
return lista;
}
**Controller:**
public ActionResult Registrar()
{
ViewBag.Message = Resources.Language.Title_Page_MC_C;
var ListaDistrito = new LNClientes().DistritoListar();
ViewBag.ObtenerDistrito = new SelectList(ListaDistrito, "IdDistrito", "DescripcionDistrito");
return View();
}
查看:
<div class="editor-field">
@Html.EditorFor(model => model.DistritoCliente)
@Html.DropDownListFor(model => model.DistritoCliente,(SelectList)ViewBag.ObtenerDistrito,"--Seleccione--")
@Html.ValidationMessageFor(model => model.DistritoCliente)
</div>
直到此时一切正常,当我打开表单中的 dropdownlistfor
工作,但是当我提交我得到了以下消息的形式:
Till this point everything is ok, when i open that form the dropdownlistfor
works but when i submit the form i got the following message:
有类型是没有ViewData的项目'的IEnumerable的
有钥匙'DistritoCliente。
There is no ViewData item of type 'IEnumerable' that has the key 'DistritoCliente'.
这是我在做什么错误或我怎么能解决这个问题的任何想法。
Any idea on what I'm doing wrong or how could i solve this problem.
先谢谢了。
亚历
推荐答案
我如何建立常用的下拉列表我都是这样
How I commonly build my dropdowns are like this
@Html.DropDownListFor(x => x.Field, PathToController.GetDropDown())
,然后在你的控制器有内置这样的方法
and then in your controller have a method built like this
public static List<SelectListItem> GetDropDown()
{
List<SelectListItem> ls = new List<SelectListItem>();
lm = (call database);
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
}
return ls;
}
希望这会有所帮助。
Hopefully it helps.
这篇关于如何填充从数据库中dropdownlistfor在ASP.NET MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!