首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SelectList的UpdateModel

使用SelectList的UpdateModel
EN

Stack Overflow用户
提问于 2009-06-21 14:21:07
回答 2查看 712关注 0票数 0

我有一个名为Product的类

代码语言:javascript
复制
public class Product
{
    public virtual int Id { get; set; }
    public virtual Category Category { get; set; }
}

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

在下面的视图中,您可以找到类别代码

EN

回答 2

Stack Overflow用户

发布于 2009-06-21 17:02:22

我找到了一种更简单的方法:

代码语言:javascript
复制
<%= Html.DropDownList("Category.Id", (System.Web.Mvc.SelectList) ViewData["categoryList"])%>
票数 1
EN

Stack Overflow用户

发布于 2009-06-21 14:46:00

如果您像这样填充ViewData["categoryList"]

代码语言:javascript
复制
ViewData["categoryList"] = categories.Select(
    category => new SelectListItem {
        Text = category.Title,
        Value = category.Id.ToString()
    }).ToList();

然后在POST操作中,您可以简单地更新您的Product.Category属性:

代码语言:javascript
复制
int categoryId;
int.Parse(Request.Form["Category"], out categoryId);

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

或者使用UpdateModel()创建用于更新的自定义ModelBinder:

代码语言:javascript
复制
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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1024007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档