2つのHtml.DropDownListをRazorで作成しました。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);
2番目の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 resultメソッドを作成しました。
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.
}
方法SubCategory
としてSelectList.DataValueField
、代わりのId
を設定するには?
あなたの質問は不明です。選択リストの値フィールドをSubCategoryにすることはどういう意味ですか? SelectListはすでにSubCategoryのリストである 'subs'によって生成されていますか?テキストフィールドをどのように設定しますか? –
SelectListのデータ値フィールドは、テキストフィールドの値に対応する必要があります。データフィールドがSubCategoryの場合、どのテキスト値が対応しますか? –
私はこの新しいSelectListのようなものをペーストしたい(サブ、 "SubCategory"、 "Subcategory")。ドロップダウンリストのすべてのオプションを使うとコントローラにSubCategoryオブジェクトの代わりにフォームを送信するときにIdだけをコントローラに送信する。コントローラは、値の代わりにProduct.SubCategoryでnullを取得します。 –