代码之家  ›  专栏  ›  技术社区  ›  HakonB

ASP.NET MVC 2 RC模型与NHibernate和下拉列表绑定

  •  4
  • HakonB  · 技术社区  · 16 年前

    应用程序有两个域实体,可以通过以下两个类来说明:

    public class Product {
        ...
    
        public Category Category { get; set; }      
    }
    
    public class Category {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    在呈现编辑表单的视图中,有以下语句显示下拉列表:

    <%= Html.DropDownListFor(model => model.Category.Id, 
           new SelectList(ViewData["categories"] as IList<Category>, "Id", "Name"), 
           "-- Select Category --" ) %>
    

    请忽略使用“非类型”视图数据来保存类别集合。

    [HttpPost]
    [TransactionFilter]
    public ActionResult Edit(int id, FormCollection collection) {
        var product = _repository.Load(id);
    
        // Update the product except the Id
        UpdateModel(product, null, null, new[] {"Id"}, collection);
    
        if (ModelState.IsValid) {
          return RedirectToAction("Details", new {id});
        }
        return View(product);
    }
    

    identifier of an instance of Name.Space.Entities.Category was altered from 4 to 2
    

    这很有意义,因为产品已经分配了一个类别,并且只有该现有类别的主键正在更改。应指定另一个类别实例。

    3 回复  |  直到 16 年前
        1
  •  2
  •   Björn Boxstart    13 年前

    我通过更改以下行解决了编辑页面上组合框的类似问题

    @Html.DropDownListFor(x => x.Employee.Id, new SelectList(ViewBag.Employees, "Id", "DisplayName"))
    

    通过

    @Html.DropDownListFor(x => x.Employee, new SelectList(ViewBag.Employees, "Id", "DisplayName"))
    

        2
  •  0
  •   Bryan    16 年前

    我以前在Linq到SQL类中使用过类似的技术,没有任何问题。我认为您不需要为此定制ModelBinder。UpdateModel应该更新传递给它的产品类,而不是附加到它的Category子类。检查DropDownListFor帮助程序生成的html。元素的名称是什么?它应该是Products表中外键字段的名称(例如,“CategoryID”或“Product.CategoryID”而不是“Category.Id”)。如果是“Category.Id”-请尝试将DropDownListFor的第一个参数更改为“model=>模型。类别“或”模型=>model.CategoryID”(或外键字段是什么)。这将导致UpdateModel只更新Product类中的外键字段,而不更新Category类ID。

        3
  •  0
  •   HakonB    15 年前

    我们当时选择的解决方案与此类似:

    TryUpdateModel(product, null, null, new[] {"Category"}, collection);
    int categoryId;
    if (int.TryParse(collection["Category.Id"], NumberStyles.Integer, CultureInfo.InvariantCulture, out categoryId) && categoryId > 0) {
        product.Category = _categoryRepository.Load(categoryId);
    }
    else {
        product.Category = null;
    }
    

    我们只是告诉模型绑定器排除关联属性并手动处理。不漂亮,但在当时工作。。。。