1

如果 MVC 只允许每个视图有一个 ViewModel,如何将下拉列表(为此需要一个单独的 ViewModel)合并到已被另一个 ViewModel 使用的现有视图中(即具有此下拉列表的列的实体)?

4

2 回答 2

3

这个问题,我猜,得到你正在寻找的一切:

如何编写一个简单的 Html.DropDownListFor()?

作为一个初学者,我只使用 NorthWind 数据库做了一个非常基本的 dropDownlist 实现。

我从 Northwind 数据库中导入了 Product & Suppliers 表。

在该ProductController.cs文件(我的Product 表的控制器文件)中,添加方法:GetAllSuppliers以获取我们将在下拉列表中显示的所有 SuppliersID。

public IEnumerable<int> GetAllSuppliers()
        {
            NorthwindEntities db = new NorthwindEntities();
            return db.Suppliers.Select(e => e.SupplierID);
        } 

现在,在 in 的Createaction 方法中ProductController.cs,传递 in 的所有值,SupplierID如下ViewData所示:

 public ActionResult Create()
            {

                ViewData["Suppliers"] = new SelectList(GetAllSuppliers());
                return View(new Product());
            } 

在您相应的Create.aspx View中,使用这个:

<%: Html.DropDownListFor(model => model.SupplierID, ViewData["Suppliers"] as SelectList) %>

以下是结果的快照:

在此处输入图像描述

如果您需要任何解释,请告诉我。

于 2013-07-27T17:39:03.997 回答
1

您可以在主 ViewModel 中创建一个属性,其中包含用于下拉列表的 ViewModel,并将其与下拉列表一起使用。

假设你有控制器。

public class HomeController
{
  public ActionResult Index()
  {
    var viewModel = new MainViewModel
    {
      SomeProperty = "SomeValue",
      DropDownData = new DropDownDataViewModel() // Initialize it with appropriate data here.
    };

    return this.View(viewModel);
  }
}

和 MainViewModel

public class MainViewModel
{
  public string SomeProperty {get; set;}
  public DropDownDataViewModel DropDownData { get; set; }
}

因此,在您的视图中,您可以调用@Model.DropDownData以访问此视图模型。

于 2013-07-27T16:26:14.870 回答