2009-06-21 35 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"])%>