0

I'm trying to update my table using Ajax Call through this code

 var customer = {};
        customer.CustomerId = row.find(".CustomerId").find("span").html();
        customer.Nome = row.find(".Nome").find("span").html();
        customer.Tipo = row.find(".Tipo").find("span").html();
        customer.NCM = row.find(".NCM").find("span").html();
        customer.Contabil = row.find(".Contabil").find("span").html();

        $.ajax({
            type: "POST",
            url: "/Home/UpdateCustomer",
            data: '{customer:' + JSON.stringify(customer) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    });

But when I click to update the value it returns a System.NullReferenceException, I can't see where I'm doing wrong.

Here's my Controller Code

 public ActionResult UpdateCustomer(Customer customer)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            Customer updatedCustomer = (from c in entities.Customers
                                        where c.CustomerId == customer.CustomerId
                                        select c).FirstOrDefault();
            updatedCustomer.Nome = customer.Nome;
            updatedCustomer.Tipo = customer.Tipo;
            updatedCustomer.NCM = customer.NCM;
            updatedCustomer.Contabil = customer.Contabil;
            entities.SaveChanges();
        }

        return new EmptyResult();
    }
Pvxtotal
  • 79
  • 7
  • 3
    You aren't sending valid JSON. `data: { customer }` should do it. Alternatively: `{ customer: customer }` or `JSON.stringify({ customer: customer })` (as a rule of thumb: *never* compose JSON by hand, and *never* use stringify unless you a) know what it does b) are absolutely positive you have to use it) –  Dec 05 '18 at 18:57
  • @ChrisG Well it worked partially, No more Exception, but now the data isn't updating in my DB. – Pvxtotal Dec 05 '18 at 19:07
  • 1
    Looking at the jQuery docs, it looks like you might have to always stringify after all; jQuery apparently turns the data into a query string otherwise. Still, you should log `entities` on the server-side to narrow down the problem. –  Dec 05 '18 at 19:10
  • The `contentType: application/json` probably is the culprit here. I created a [fiddle](https://dotnetfiddle.net/mF43mr) to demonstrate passing table contents through AJAX and getting results, just using `data: customer` and remove the `contentType` option from AJAX callback. – Tetsuya Yamamoto Dec 06 '18 at 02:45

2 Answers2

1

System.NullReferenceException revealed the value updatedCustomer or customer is null.You need check which is null.

And when you want to update a enity in EF,you need add code like :

    context.Entry(existingBlog).State = EntityState.Modified;

Howerver,Why you need Query A Entity befor update?I guess you want to do this:

    public ActionResult UpdateCustomer(Customer customer)
    {
      using (CustomersEntities entities = new CustomersEntities())
       {
          entities.Entry(customer).State = EntityState.Modified;
          entities.SaveChanges();
       }
       return new EmptyResult();
    }
Winter
  • 183
  • 5
1

This AJAX callback below actually passed JSON string containing JSON object, which is wrong and causing customer contains null value which throwing NullReferenceException (it is strongly advised to put null check before using EF entity context):

$.ajax({
    type: "POST",
    url: "/Home/UpdateCustomer",
    data: '{customer:' + JSON.stringify(customer) + '}', // this is wrong 
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

Instead of passing JSON string like that, just use data: JSON.stringify(customer) or simply passing entire object directly with data: customer and remove contentType setting:

$.ajax({
    type: "POST",
    url: "/Home/UpdateCustomer",
    data: customer, 
    dataType: "json",
    success: function (result) {
        // do something
    }
});

Regarding second issue which selected data from table query is not updated, it depends on auto-tracking setting from EF. If auto-tracking is disabled, you need to set EntityState.Modified before using SaveChanges():

if (customer != null)
{
    using (CustomersEntities entities = new CustomersEntities())
    {
        Customer updatedCustomer = (from c in entities.Customers
                                    where c.CustomerId == customer.CustomerId
                                    select c).FirstOrDefault();

        updatedCustomer.Nome = customer.Nome;
        updatedCustomer.Tipo = customer.Tipo;
        updatedCustomer.NCM = customer.NCM;
        updatedCustomer.Contabil = customer.Contabil;

        // if EF auto-tracking is disabled, this line is mandatory 
        entities.Entry(updatedCustomer).State = System.Data.Entity.EntityState.Modified;
        entities.SaveChanges();
    }
}

Notes:

1) You can see all methods to update existing data with EF in this reference.

2) This fiddle contains sample to make AJAX request from a table contents.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • It continues giving me NullReference Exception, what I noticed is that it doesn't matter which field I update, the exception only happens in this line updatedCustomer.Nome = customer.Nome; – Pvxtotal Dec 06 '18 at 12:25