如何在 ASP.NET MVC 3 中为填充的下拉列表创建视图模型 [英] How do I create a view model for a populated drop down list in ASP.NET MVC 3

查看:20
本文介绍了如何在 ASP.NET MVC 3 中为填充的下拉列表创建视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自学 MVC3.我是从网络表单转换过来的.

I'm trying to teach myself MVC3. Im converting from webforms.

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

I need to create a view model that includes a dropdown list that I can pass to the controller and eventually render in the View.

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

How can I accomplish this? I have the skeleton but I dont know what the code is to actually create the name value pairs for the view.

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>
         }
     }
  }

谢谢

推荐答案

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

I would create a class for Product and the create Products Property in my main viewmodel which is of type 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;}    
}

并在您的控制器操作方法中

and in your Controller Action method

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);
}

在您的视图中,它是强类型的 OrderViewModel.

and in your view which is strongly typed to OrderViewModel.

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

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

I have added a SelectedProductId property also, so you will get the user selected value from the dropdown in that Property when user post the form back to the controller.

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

You can also use the generic SelectListItem type collection as your view model property to transfer the dropdown data instead of your custom ProductViewModel collection.

public class OrderViewModel
{
  public int OrderNumber { set;get;}
  public List<SelectListItem> Products { set;get;}
  public int SelectedProductId { set;get;}    
}

在 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);
}

在您看来,

@Html.DropDownListFor(x => x.SelectedProductId, Model.Products, "-- Select Product--")

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

EDIT : As per the request from OP, edited the answer to have the Property returning static items as products

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

I added a get implementation to Products property to return a list of static products.

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;}
}

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

Now in your controller, you don't need to call the GetAvailableProductsmethod as it is already there. So the controller will looks like this.

    public ActionResult Order()
    {
        OrderViewModel orderVM = new OrderViewModel();           
        return View(orderVM);
    }

这是输出.

如果产品中有很多项目,请将其移动到一个方法并调用该方法并获取实现,而不是在那里编写.这是更简洁的方法.

If you have many items in the products, move it to a method and call that method int he get implementation instead of writing that there. That is much cleaner approach.

这篇关于如何在 ASP.NET MVC 3 中为填充的下拉列表创建视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆