2009-06-21 31 views
1

我有一个名为类产品的UpdateModel用的SelectList

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

请告诉我如何更新的UpdateModel方法分类。

下面你会发现在查看

回答

1

类别代码如果您填充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()更新创建自定义模型绑定器:

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); 
    } 
} 
1

我已经找到了一种更简单的方式做呢:

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