views:

318

answers:

2

Hello, I have class named Product

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

Please tell me how to update Category with UpdateModel method.

Below you'll find category code in View

<%= Html.DropDownList("Category", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>

+1  A: 

If you are populating ViewData["categoryList"] like this:

ViewData["categoryList"] = categories.Select(
    category => new SelectListItem {
        Text = category.Title,
        Value = category.Id.ToString()
    }).ToList();

then in your POST action, you can simply update your Product.Category property:

int categoryId;
int.Parse(Request.Form["Category"], out categoryId);

product.Category = categories.First(x => x.Id == categoryId);

or create custom ModelBinder for updating with 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);
    }
}
eu-ge-ne
+1  A: 

I've found a easier way do do it:

<%= Html.DropDownList("Category.Id", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>
k1