Productという名前のクラスがあります
public class Product
{
public virtual int Id { get; set; }
public virtual Category Category { get; set; }
}
UpdateModelメソッドでカテゴリを更新する方法を教えてください。
以下に、ビューのカテゴリ コードがあります。
Productという名前のクラスがあります
public class Product
{
public virtual int Id { get; set; }
public virtual Category Category { get; set; }
}
UpdateModelメソッドでカテゴリを更新する方法を教えてください。
以下に、ビューのカテゴリ コードがあります。
私はそれを行うより簡単な方法を見つけました:
<%= Html.DropDownList("Category.Id", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>
このように入力している場合ViewData["categoryList"]
:
ViewData["categoryList"] = categories.Select(
category => new SelectListItem {
Text = category.Title,
Value = category.Id.ToString()
}).ToList();
次に、POST アクションで、Product.Category プロパティを更新するだけです。
int categoryId;
int.Parse(Request.Form["Category"], out categoryId);
product.Category = categories.First(x => x.Id == categoryId);
または、UpdateModel() で更新するためのカスタム ModelBinder を作成します。
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (String.Compare(propertyDescriptor.Name, "Category", true) == 0)
{
int categoryId = (int)bindingContext.ValueProvider["tags"].RawValue;
var product = bindingContext.Model as Product;
product.Category = categories.First(x => x.Id == categoryId);
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}