TryUpdateModel 忽略 GridView 的 Visible="false" 列中的属性

TryUpdateModel ignoring properties in Visible="false" columns of GridView

所以我在这里有我的 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 上有很多列,因此我们根据用户选择显示和隐藏一些列。 我遇到的问题是,任何绑定到 Visible="false" 列的属性都没有在 TryUpdateModel() 期间设置,因此填充了默认值。这意味着,例如,如果用户看不到价格详细信息,则在保存时他们的价格将设置为 0。

事实证明,该解决方案实际上非常简单,但对数据库来说要贵一些。

我们从当前数据库值中获取重新映射模型所需的相关实体,一旦我们从当前数据库值中获得模型,我们就可以对该模型执行更新,这将留下 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;
    }
}

希望这对其他人有帮助。