简体   繁体   English

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

[英]TryUpdateModel ignoring properties in Visible=“false” columns of GridView

So I have my UpdateMethod here: 所以我在这里有我的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;
    }
}

It's using AutoMapper to map from a Model for the ProductList page across to the Product Entity. 它使用AutoMapper从ProductList页面的Model映射到Product Entity。 There are a lot of columns on the GridView so we're showing and hiding some based on user selections. GridView上有很多列,因此我们根据用户选择显示和隐藏一些列。 The issue I'm having is that any properties bound to a Visible="false" column are not being set during TryUpdateModel() and are thus populated with the defaults. 我遇到的问题是在TryUpdateModel()期间未设置任何绑定到Visible =“ false”列的属性,因此使用默认值进行填充。 This means that for example if the user doesn't have price details visible, their price gets set to 0 when they save. 这意味着,例如,如果用户看不到价格明细,则保存时其价格将设置为0。

So it turns out that the solution is in fact quite simple if somewhat more expensive for the database. 因此,事实证明,该解决方案实际上非常简单,即使对于数据库而言稍微贵一些。

We fetch the related entities needed to remap the model from the current database values, once we have our model from the current DB values, we can then perform the update on that model which will leave the Visible="false" columns unchanged from their DB values. 我们从当前数据库值中获取重新映射模型所需的相关实体,一旦我们从当前数据库值中获取了模型,便可以对该模型执行更新,这将使Visible =“ false”列与数据库保持不变值。

We then map the model back to the entity and persist this back to the DB as per before. 然后,我们将模型映射回实体,并按照之前的方法将其持久化回数据库。

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;
    }
}

Hope this helps someone else. 希望这对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM