Click here to Skip to main content
15,851,701 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Problem

when save data from controller when click create button to save i get error

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
WebTabCore.Controllers.SalesOrderController.Create(SalesHeader sh) in SalesOrderController.cs, line 37

Stack Query Cookies Headers
NullReferenceException: Object reference not set to an instance of an object.
WebTabCore.Controllers.SalesOrderController.Create(SalesHeader sh) in SalesOrderController.cs
+
foreach (var i in sh.SalesFooters)

Header data not have any problem

Model used for save is

C#
public class SalesHeader
        {
        public int SalesOrderNo { get; set; }
        public int SalesYear { get; set; }
        public int BranchCode { get; set; }
        public int SalesType { get; set; }
        public DateTime SalesDate { get; set; }
        public int CustomerID { get; set; }
        public Customer Customers { get; set; }
        public ICollection<salesfooter> SalesFooters { get; set; }
        public decimal TotalPrice { get; set; }
         }
on create view i add items to list as following

 if (isValidItem) {
                orderItems.push({
                    SalesLineNo: $('#SalesLineNo').val().trim(),
                    ItemCode: $('#ItemCode').val().trim(),
                    Quantity: parseInt($('#Qunatity').val().trim()),
                    UnitPrice: parseFloat($('#UnitPrice').val().trim()),
                    Total: parseInt($('#Qunatity').val().trim()) * parseFloat($('#UnitPrice').val().trim())
                });
when save data i use as following

I assign on code below

SalesFooters: orderItems

  //save data
    $('#submit').click(function () {
        //validation of order
        var isAllValid = true;
        if (orderItems.length == 0) {
            $('#orderItems').html('<span style="color:red;">Please add order items</span>');
            isAllValid = false;
        }

        
        //Save if valid
        if (isAllValid) {
            var data = {
                SalesOrderNo: $('#SalesOrderNo').val().trim(),
                SalesYear: $('#SalesYear').val().trim(),
                BranchCode: $('#BranchCode').val().trim(),
                SalesType: $('#SalesType').val().trim(),
                SalesDate: $('#SalesDate').val().trim(),
                CustomerID: $('#CustomerID').val().trim(),
                TotalPrice: $('#TotalPrice').val().trim(),
                SalesFooters: orderItems
            }

            $(this).val('Please wait...');

            $.ajax({
                url: '/SalesOrder/Create',
                type: "POST",
                data: JSON.stringify(data),
                dataType: "JSON",
                contentType: "application/json",
                success: function (d) {
                    //check is successfully save to database 
                    if (d.status == true) {
                        //will send status from server side
                        alert('Successfully done.');
                        //clear form
                        orderItems = [];
                        $('#SalesOrderNo').val('');
                        $('#SalesYear').val('');
                        $('#BranchCode').val('');
                        $('#SalesType').val('');
                        $('#SalesDate').val('');
                        $('#CustomerID').val('');
                        $('#TotalPrice').val('');
                        $('#orderItems').empty();
                    }
                    else {
                        alert('Failed');
                    }
                    $('#submit').val('Save');
                },
                error: function () {
                    alert('Error. Please try again.');
                    $('#submit').val('Save');
                }
            });


What I have tried:

[HttpPost]
        public JsonResult Create(SalesHeader sh)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
              
                    SalesHeader order = new SalesHeader { SalesOrderNo = sh.SalesOrderNo, SalesType = sh.SalesType, BranchCode = sh.BranchCode,SalesYear=sh.SalesYear,SalesDate=sh.SalesDate,CustomerID=sh.CustomerID };
                    foreach (var i in sh.SalesFooters) here exception done
                    {
                    SalesFooter sf = new SalesFooter();
                    sf.SalesLineNo = i.SalesLineNo;
                    sf.ItemCode = i.ItemCode;
                    sf.Quantity = i.Quantity;
                    sf.UnitPrice = i.UnitPrice;
                    sf.Total = i.Total;
                    
                        order.SalesFooters.Add(i);
                    }
                _repository.Insert(order);
                status = true;

              

            }
            else
            {
                status = false;
               
            }
           
            return Json (sh);
        }
Posted
Updated 20-Jan-19 9:47am
v2

1 solution

There is an issue in .net core when passing the complex object over the wire
The workaround is to use [FromBody]
C#
public JsonResult Create([FromBody] SalesHeader sh)

Please, refer this SO question for more details.
Still, I suggest you to implement null reference checking in your controller since your API can crash if invalid data is passed
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900