从Model创建Html.DropDownList?

时间:2013-04-23 22:03:49

标签: c# asp.net-mvc razor asp.net-mvc-4 html-select

我需要在我的mvc应用程序中创建一个发票功能。我有这个模特课:

public class Product
{
    public int ProductId { get; set; }
    public int SupplierId { get; set; }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public double costPrice { get; set; }
    public string ProductPicUrl { get; set; }
    public ProductCategory Category { get; set; }
    public Supplier Supplier { get; set; }
}

1.我需要让我的视图显示所有产品(特别是所有产品名称)的下拉列表,而不使用ViewData 2.我需要能够单击一个转到我的AddToInvoice控制器方法的按钮。我只是不确定如何将productid从下拉列表中拉出来并将其发送到方法。

有人可以帮忙吗?即使只是为了解释如何制作下拉列表?

1 个答案:

答案 0 :(得分:3)

我通常会创建一个视图模型,其中既包含我要创建或更新的模型,也包含为特定字段提供数据所需的项目列表。在这种情况下,我将创建一个名为SelectProductModel的视图模型,其中包含ProductId属性和Products属性。

public class SelectProductModel
{

  public Int32 ProductId { get; set; }
  public IEnumerable<Product> Products { get; set; }

}

Invoice控制器中,我只需加载产品列表并将其存储在模型中:

public ActionResult SelectProduct()
{
  SelectProductModel model = new SelectProductModel();
  model.ProductId = -1;
  model.Products = productRepository.GetList();
  return View();
}

public ActionResult AddToInvoice(Int32? id)
{
  //id is the ProductId sent
}

SelectProduct视图将是基于此模型的类型化视图:

@model SelectProductModel
...
@using(Html.BeginForm(actionName="AddToInvoice", controllerName="Invoice", method=FormMethod.Post))
{

  @Html.DropDownListFor(m => m.ProductId, new SelectList(model.Products, "ProductId", "Name"))
}
相关问题