如何在ASP.NET MVC 3中为填充的下拉列表创建视图模型

Mad*_*r24 19 c# asp.net asp.net-mvc-3

我正在尝试自学MVC3.我是从webforms转换而来的.

我需要创建一个视图模型,其中包含一个下拉列表,我可以将其传递给控制器​​并最终在视图中呈现.

我怎么能做到这一点?我有骨架,但我不知道实际为视图创建名称值对的代码是什么.

namespace DH.ViewModels
{
    public class SharedLayoutViewModel
    {
        public IEnumerable<SelectListItem> Products
        {
            //some code to setup the value/name pairs to be rendered in the view.
            //example: 
            //<option value="1">Mustard</option>
            //<option value="2">Ketchup</option>
            //<option value="3">Mayo</option>
            //<option value="4">Relish</option>
            //<option value="5">BBQ</option>
         }
     }
  }
Run Code Online (Sandbox Code Playgroud)

谢谢

Shy*_*yju 37

我将在我的主视图模型中为Product创建一个类并创建Products属性,该类型为List

public class ProductViewModel
{
  public int ID { set;get;}
  public string Name { set;get;}
}

public class OrderViewModel
{
  public int OrderNumber { set;get;}
  public List<ProductViewModel> Products { set;get;}
  public int SelectedProductId { set;get;}    
}
Run Code Online (Sandbox Code Playgroud)

并在您的Controller Action方法中

public ActionResult Order()
{     
   var orderVM=new OrderViewModel();
   //Items hard coded for demo. You may replace with values from your db
   orderVM.Products= new List<ProductViewModel>
    {
        new ProductViewModel{ ID=1, Name="IPhone" },
        new ProductViewModel{ ID=2, Name="MacBook Pro" },
        new ProductViewModel{ ID=3, Name="iPod" }           
    };
   return View(orderVM);
}
Run Code Online (Sandbox Code Playgroud)

并在您的视图中强烈键入OrderViewModel.

@model ORderViewModel
@using (Html.BeginForm())
{
  <p> 
    @Html.DropDownListFor(x => x.SelectedProductId ,
                     new SelectList(Model.Products, "ID", "Name"), "-- Select Product--")
  </p>
  <input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)

我还添加了一个SelectedProductId属性,因此当用户将表单发布回控制器时,您将从该属性的下拉列表中获取用户选择的值.

您还可以使用泛型SelectListItem类型集合作为视图模型属性来传输下拉数据而不是自定义ProductViewModel集合.

public class OrderViewModel
{
  public int OrderNumber { set;get;}
  public List<SelectListItem> Products { set;get;}
  public int SelectedProductId { set;get;}    
}
Run Code Online (Sandbox Code Playgroud)

在GET行动中,

public ActionResult Order()
{     
   var orderVM=new OrderViewModel();
   //Items hard coded for demo. You may replace with values from your db
   orderVM.Products= new List<SelectListItem>
    {
        new SelectListItem {Value = "1", Text = "IPhone"},
        new SelectListItem {Value = "2", Text = "MacBook"},
        new SelectListItem {Value = "3", Text = "Candy"}
    };
   return View(orderVM);
}
Run Code Online (Sandbox Code Playgroud)

在你看来,

@Html.DropDownListFor(x => x.SelectedProductId, Model.Products, "-- Select Product--")
Run Code Online (Sandbox Code Playgroud)

编辑:根据OP的请求,编辑答案,让属性返回静态项目作为产品

我在Products属性中添加了一个get实现,以返回静态产品列表.

public class OrderViewModel
{
        private List<ProductViewModel> _products;
        public int OrderNumber { set; get; }
        public List<ProductViewModel> Products
        {
            get
            {
                if (_products == null)
                {
                    _products = new List<ProductViewModel>();
                    _products.Add(new ProductViewModel { ID = 1, Name = "Ketchup" });
                    _products.Add(new ProductViewModel { ID = 1, Name = "Mustard" });
                    _products.Add(new ProductViewModel { ID = 1, Name = "Relish" });
                    _products.Add(new ProductViewModel { ID = 1, Name = "Mayo" });
                }
                return _products;
            }
        }
       public int SelectedProductId { set;get;}
}
Run Code Online (Sandbox Code Playgroud)

现在在您的控制器中,您不需要调用GetAvailableProducts方法,因为它已经存在.所以控制器看起来像这样.

    public ActionResult Order()
    {
        OrderViewModel orderVM = new OrderViewModel();           
        return View(orderVM);
    }
Run Code Online (Sandbox Code Playgroud)

这是输出. 在此输入图像描述

如果产品中有许多项目,请将其移至方法并调用该方法,以获得实现,而不是在那里编写.这是更清洁的方法.


lah*_*rah 6

我更喜欢这样做.

@Html.DropDownListFor(m => m.ProductId, new SelectList(Model.Products, "ID", "Name"))
Run Code Online (Sandbox Code Playgroud)

所以我的视图模型只包含一个产品列表,并在视图上生成选择列表.