0

Productという名前のクラスがあります

public class Product
{
    public virtual int Id { get; set; }
    public virtual Category Category { get; set; }
}

UpdateModelメソッドでカテゴリを更新する方法を教えてください。

以下に、ビューのカテゴリ コードがあります。

4

2 に答える 2

1

私はそれを行うより簡単な方法を見つけました:

<%= Html.DropDownList("Category.Id", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>
于 2009-06-21T17:02:22.307 に答える
0

このように入力している場合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);
    }
}
于 2009-06-21T14:46:00.107 に答える