我有一个名为Product的类
public class Product
{
public virtual int Id { get; set; }
public virtual Category Category { get; set; }
}请告诉我如何使用UpdateModel方法更新类别。
在下面的视图中,您可以找到类别代码
发布于 2009-06-21 17:02:22
我找到了一种更简单的方法:
<%= Html.DropDownList("Category.Id", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>发布于 2009-06-21 14:46:00
如果您像这样填充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);
}
}https://stackoverflow.com/questions/1024007
复制相似问题