【问题标题】:TryUpdateModel ignoring properties in Visible="false" columns of GridViewTryUpdateModel 忽略 GridView 的 Visible="false" 列中的属性
【发布时间】:2015-07-09 11:21:29
【问题描述】:

所以我在这里有我的 UpdateMethod:

public void gvProducts_UpdateItem(Int32 ProductID)
{
    ProductListModel model = new ProductListModel();

    Product product = db.Products.Find(ProductID);

    if (product == null)
    {
        // MAF: The item wasn't found
        ModelState.AddModelError("", String.Format("Item with id {0} was not found", ProductID));
        return;
    }

    TryUpdateModel(model);

    if (ModelState.IsValid)
    {
        Mapper.Map(model, product);
        db.SaveChanges();
        gvProducts.EditIndex = -1;
    }
}

它使用 AutoMapper 从 ProductList 页面的模型映射到产品实体。 GridView 上有很多列,因此我们根据用户选择显示和隐藏一些列。 我遇到的问题是在 TryUpdateModel() 期间未设置绑定到 Visible="false" 列的任何属性,因此填充了默认值。这意味着,例如,如果用户看不到价格详情,他们的价格会在保存时设置为 0。

【问题讨论】:

    标签: c# asp.net gridview webforms model-binding


    【解决方案1】:

    所以事实证明,如果数据库的成本稍微高一些,该解决方案实际上是相当简单的。

    我们从当前数据库值中获取重新映射模型所需的相关实体,一旦我们从当前数据库值中获取模型,我们就可以对该模型执行更新,这将使 Visible="false" 列保持不变来自他们的 DB 值。

    然后我们将模型映射回实体,并像以前一样将其持久化回数据库。

    public void gvProducts_UpdateItem(Int32 ProductID)
    {
        Product product = db.Products
                            .Include(it => it.TaxRate)
                            .Include(it => it.Category)
                            .Include(it => it.Brand)
                            .Include(it => it.Supplier)
                            .Include(it => it.Colour)
                            .FirstOrDefault(it => it.ProductID == ProductID);
    
        if (product == null)
        {
            ModelState.AddModelError("", String.Format("Item with id {0} was not found", ProductID));
            return;
        }
    
        ProductListModel model = Mapper.Map<ProductListModel>(product);
    
        TryUpdateModel(model);
    
        if (ModelState.IsValid)
        {
            Mapper.Map(model, product);
            db.SaveChanges();
            gvProducts.EditIndex = -1;
        }
    }
    

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多