添加在MVC一个DropDownList [英] Adding a dropdownlist in MVC
问题描述
如果MVC只允许你有每查看某个视图模型,一个人如何融入一个DropDownList(需要有这样一个独立的视图模型),其中已被其他视图模型现有的View(即其中有一栏的实体这个DropDownList的)?
If MVC only allows you to have one ViewModel per View, how does one incorporate a dropdownlist (need to have a separate ViewModel for this) into an existing View which is already used by another ViewModel (ie an entity which has a column for this dropdownlist)?
推荐答案
此问题,此外,我想,有你正在寻找的一切:
This Question in addition, I guess, Got everything you are looking for:
如何写一个简单的Html.DropDownListFor()?
作为一个初学者,我只做使用Northwind数据库DROPDOWNLIST的一个非常基本的实现。
As a beginner, I did a very basic implementation of dropDownlist using the NorthWind Database only.
我已经导入的产品和放大器;供应商表从Northwind数据库。
I had imported the Product & Suppliers table from Northwind database.
在 ProductController.cs
文件,这是对我的产品
表控制器文件,添加方法: GetAllSuppliers
来得到所有SuppliersID,我们将在下拉列表显示。
In the ProductController.cs
file, which is the controller file for my Product
table, add method: GetAllSuppliers
to get all SuppliersID which we will display in a dropdown.
public IEnumerable<int> GetAllSuppliers()
{
NorthwindEntities db = new NorthwindEntities();
return db.Suppliers.Select(e => e.SupplierID);
}
现在,在创建
操作方法,通过<$ C $的所有值C>供应商ID 在 ProductController.cs
的ViewData code>,如下图所示:
Now, in the Create
action method in ProductController.cs
, pass all the values of SupplierID
in ViewData
as seen below:
public ActionResult Create()
{
ViewData["Suppliers"] = new SelectList(GetAllSuppliers());
return View(new Product());
}
在您相应的 Create.aspx查看
,使用:
<%: Html.DropDownListFor(model => model.SupplierID, ViewData["Suppliers"] as SelectList) %>
下面是结果的快照:
Below is a snapshot of the Result:
让我知道如果你需要任何解释。
Let me know if you need any explanation.
这篇关于添加在MVC一个DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!