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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9882700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:03:39  来源:igfitidea点击:

How do I create a view model for a populated drop down list in ASP.NET MVC 3

c#asp.netasp.net-mvc-3

提问by Maddhacker24

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

我正在尝试自学MVC3。我从网络表单转换。

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

Thanks

谢谢

采纳答案by Shyju

I would create a class for Product and the create Products Property in my main viewmodel which is of type List

我将为 Product 创建一个类,并在我的主视图模型中创建一个 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);
}

and in your view which is strongly typed to OrderViewModel.

并在您的视图中强类型为 OrderViewModel。

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

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

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

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

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

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

and in the GET action,

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

And in your view,

而在你看来,

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

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

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

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

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

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

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

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

Here is the output. enter image description here

这是输出。 在此处输入图片说明

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.

如果产品中有很多项目,请将其移动到一个方法并调用该方法 int he get implementation 而不是在那里编写。这是一种更清洁的方法。

回答by lahsrah

I prefer to do it this way.

我更喜欢这样做。

@Html.DropDownListFor(m => m.ProductId, new SelectList(Model.Products, "ID", "Name"))

So my view model just contains a list of products and generate the select list on the view.

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

回答by amdmax

Why can't you just use SelectList within your ViewModel? It's kind of abstraction that contains selected value and list of items itself. You can implement Display / Editor templates and define attribute DataTypeAttribute/UIHintAttribute associate specific template with Select List.

为什么不能在 ViewModel 中使用 SelectList?这是一种包含选定值和项目列表本身的抽象。您可以实现显示/编辑器模板并定义属性 DataTypeAttribute/UIHintAttribute 将特定模板与选择列表关联。

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