0

我有一个名为 Product 的类

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

请告诉我如何使用 UpdateModel 方法更新类别。

下面你会在视图中找到类别代码

4

2 回答 2

1

I've found a easier way do do it:

<%= 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);

或创建自定义 ModelBinder 以使用 UpdateModel() 进行更新:

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 回答