我用Razor創建了2個Html.DropDownList。如何將SelectList.DataValueField設置爲List的整個對象?
<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
?
你的問題不清楚。你是什麼意思使選擇列表的值域是子類別? SelectList已經由'subs'生成,它是一個SubCategory類型的列表?你會如何設置文本框? –
SelectList中的數據值字段應該對應於文本字段的值。所以如果你的數據字段是SubCategory,那麼對應的文本值是什麼? –
我想粘貼一些像這樣新的SelectList(subs,「SubCategory」,「Subcategory」)。在dropdownlist中包含所有選項,當我提交表單時,只發送Id到控制器,而不是SubCategory對象到controller。這就是爲什麼在控制器我在Product.SubCategory中獲取null而不是值。 –