【问题标题】:Bind not working as expecting绑定没有按预期工作
【发布时间】:2016-01-05 00:46:27
【问题描述】:

我似乎遗漏了一些明显的东西。我在编辑方法中使用 Bind 仅更新 Bind 中列出的字段。但是,所有字段都在更新,并且由于许多字段未包含在表单帖子中,因此这些字段被覆盖并设置为 null。我只想更新 Bind 中列出的字段。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "customerid,firstname,lastname,businessid,userid")] customers customers)
    {

        if (ModelState.IsValid)
        {
            db.Entry(customers).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
...
    }

【问题讨论】:

    标签: c# asp.net-mvc entity-framework


    【解决方案1】:

    我的猜测是您没有在表单中包含这些字段。因此,当提交表单时,这些属性值将返回为 null 并且模型绑定器使用创建的(由模型绑定器)customers 对象上的空值。保存对象时,将在这些属性/字段上保存空值。

    理想情况下,您应该做的是,在您的 HttpPost 操作中再次读取实体并仅更新您想要更新的属性

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "CustomerId,FirstName)] 
                                                                              Customers model)
    {
    
        if (ModelState.IsValid)
        {
          var c = db.Customers.FirstOrDefault(s=>s.CustomerId==model.CustomerId);
          if(c!=null)
          {
             c.FirstName = model.FirstName; //update the property value
    
             db.Entry(c).State = EntityState.Modified;
             await db.SaveChangesAsync();
             return RedirectToAction("Index");
          }
        }
    
     }
    

    另外,如果您愿意,您可以考虑使用视图模型(特定于您的视图)在您的操作方法和视图之间传递数据,以更新您的数据,如this answer 中所述。

    【讨论】:

    • 您也可以使用 TryUpdateModel() 代替手动将每个值分配给刚刚读取对象的属性。
    【解决方案2】:

    您可以选择要更新的属性:

    if (ModelState.IsValid)
    {
        db.Customers.Attach(customers);
        var entry = db.Entry(customers);
        entry.Property(e => e.customerid).IsModified = true;
        entry.Property(e => e.firstname).IsModified = true;
        ...
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    

    【讨论】:

    • 认为这就是 Bind 的全部目的。将不得不阅读更多。谢谢。立即使用这两个答案。
    • 不,Bind 属性的目的是决定从 HTTP 请求中绑定哪些属性。它与实体框架完全无关。它是纯粹的 ASP.NET MVC 工件。
    • 达林·季米特洛夫!伙计,你真棒。尊重!
    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多