question

RonaldRex-2335 avatar image
0 Votes"
RonaldRex-2335 asked RonaldRex-2335 commented

Receiving Runtime Error System.NullReferenceException in Put Method

I am receiving a runtime error message...... System.NullReferenceException: 'Object reference not set to an instance of an object.' at this line of code entity.ProductName = product.ProductName;
The code where the System.NullReferenceException error is occuring is inside a ASP.Net Web API project that i am calling using ajax jquery put request inside of a javascript project.
I have determined that I am receiving this System.NullReferenceException error because I am trying to update a record that I selected from the jquery datatable that has been deleted from the underlying database
I want a message that the record has been deleted please Refresh your browser or if you can think of another elegant way to end the pending transaction so that the end user won't incur an error that is fine as well. Should I check to see if the entity reference variable is null? I am just trying to figure out what is the best Practice for handling this problem. I have attached the code below. Thanks !!!

public void Put(int id, [FromBody] Product product)
{

         using(BookStoresDBEntities entities=new BookStoresDBEntities())
         {
             try
             { 
                var entity = entities.Products.FirstOrDefault(p => p.ProductId == id);
                entity.ProductName = product.ProductName;
                entity.IntroductionDate = product.IntroductionDate;
                entity.Url = product.Url;
                entities.SaveChanges();
             }
             catch (DbEntityValidationException e)
             {
                 foreach (var eve in e.EntityValidationErrors)
                 {
                     Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                         eve.Entry.Entity.GetType().Name, eve.Entry.State);
                     foreach (var ve in eve.ValidationErrors)
                     {
                         Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                             ve.PropertyName, ve.ErrorMessage);
                     }
                 }
                 throw;
             }
         }
     }

dotnet-aspnet-general
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered RonaldRex-2335 commented

these lines

 var entity = entities.Products.FirstOrDefault(p => p.ProductId == id);
 entity.ProductName = product.ProductName;

if not found, entity will be null so the second line will throw an error. you might want to try an if statement:

 var entity = entities.Products.FirstOrDefault(p => p.ProductId == id);
 if (entity == null)
 {
      // no record message
 }


· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your help. Your suggestion seems straightforward. I was wondering how do I propagate that message from the Web API to the client or where the Ajax method made the call. And would that error be in the Ajax function Error or this part of the code...


 f`unction productUpdate(product) {
             $.ajax({
                           url: "/api/Products/" + product.ProductId,
                           type: 'PUT',
                           contentType: "application/json;charset=utf-8",
                           data: JSON.stringify(product),
                           success: function (product) {
                           productUpdateSuccess(product);
                              
                           },
                           error: function (request, message, error) {
                       
                          }
                      });
     }


0 Votes 0 ·

Hi @RonaldRex-2335 ,
I suggest you could check by yourself.Just do like this:
1.Press F12 when you are running your project.
2.Select at "Source" menu and breakpoint at your ajax source.
3.If you run the url to the put method,you could check your error in "Network" menu.
4.If your ajax is right,you will run the put method in the code behind.
5.If you could return the right value in the code behind, the ajax success function will return the value.

Best regards,
Yijing Sun

1 Vote 1 ·

Thank You Very Much !!!

0 Votes 0 ·

I don't know what you are referring to as code behind. I dont put code behind my events anymore. This is Ajax jquery callind a Web Api.

0 Votes 0 ·