如何将SelectList.DataValueField设置为List的整个对象?

时间:2016-07-26 18:55:01

标签: c# asp.net-mvc

我用Razor创建了2个Html.DropDownList。

 <p>Category:</p>
        @Html.DropDownList("Category", new SelectList(catList, "Id", "category"), "Select category");
        <p>SubCategory:</p> 
        @Html.DropDownListFor(x=>x.SubCategory, new SelectList(string.Empty, "Id", "Subcategory"), "Select sub category",new {id="subCategory" });
        @Html.ValidationMessageFor(x => x.SubCategory);

第二个DropDownListFor的模型看起来像这样。

namespace OnlineShop.Models

{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    public partial class Product
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Enter name of product")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Enter article of product")]
        public string Article { get; set; }
        [Required(ErrorMessage = "Enter description of product")]
        public string Description { get; set; }
        [Required(ErrorMessage = "Enter price of product")]
        public decimal Price { get; set; }
        [Required(ErrorMessage = "Select picture of product")]
        public byte[] Picture { get; set; }
        [Required(ErrorMessage = "Enter date of product")]
        public System.DateTime DateAdded { get; set; }
        [Required(ErrorMessage = "Choose subcategory of product")]
        public virtual SubCategory SubCategory { get; set; }//property that i want to associate with SelectList.DataValueField.
    }
}

然后我创建了JSon结果方法。

  public JsonResult GetSubs(int category)
    {
        List<SubCategory> subs = goods.SubCategorySet.Where(x=>x.Category.Id==category).ToList();
        return Json(new SelectList(subs, "Id", "Subcategory")); //here is row of code that i want to change.
    }

如何将SelectList.DataValueField设置为SubCategory,而不是Id

1 个答案:

答案 0 :(得分:1)

我很确定你无法在下拉列表中加载子类别类。但您可以做的是从下拉列表中保存ID并使用该ID从数据库中检索相应的项目,然后将其添加到您的实体。

您可以在操作参数列表中创建一个参数,其名称和类型与下拉列表相同,以便检索该值。

@Html.DropDownList("SubCategoryID", ViewBag.Subs, "Select an Option", new { @class = "pretty" })

[HttpPost]
 public ActionResult Index(Product model, int SubCategoryID)
{

  //here you can retrieve your item from the database using the value in
  //SubCategoryID
  //Psuedo code below:

  Subcategory test = goods.SubCategorySet.Where(sc => sc.id == SubCategoryID);

  model.SubCategory = test;

  //save/update model here
}

在您创建新产品子类别时,在回发后将为null,但是当您使用ID分配所选子类别时。

如果您在实体的编辑屏幕上,您还将使用该ID显示当前选定的子类别。只需获取id并在选择列表的selected value属性中使用它。

new SelectList(subs, "Id", "Subcategory", SubCategoryID));