0

I have been doing some research on how to serialize a datatable to json string. The below code works and is displaying in my API but with back slashes. I have done some research and know that the slashes are happening because I am serializing the data twice. What I dont know is how to fix this issue. I am using MVC and calling the api via jquery.

Here is code that creates JSON String:

 _sql = "EXEC [dbo].[GetInvoiceAllTotals] @DateRange = '" + dateRange + "', @AcctGuid = '" + userAccountID.AccountGUID + "'";
        _table = Functions.DataTable(_sql);

        List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
        Dictionary<string, object> item;
        foreach (DataRow row in _table.Rows)
        {
            item = new Dictionary<string, object>();
            foreach (DataColumn col in _table.Columns)
            {
                item.Add(col.ColumnName, (Convert.IsDBNull(row[col]) ? null : row[col]));
            }
            lst.Add(item);
        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(lst);

Here are the results:

"[{\"NoInvoices\":2,\"InvoiceTotals\":null,\"NoPayments\":0,\"PaymentTotals\":null}]"

I would like the results to return like this:

[ { "NoInvoices": 2, "InvoiceTotals": null, "NoPayments": 0, "PaymentTotals": null } ]

I call the API with the below code

            $.ajax({
                 url:"/api/InvoiceTotal/?dateRange=" + $('#dateFilterBy').val(),
                 dataType: 'json',
                 success: function (data) {
                      //handle the json response
                     console.log(data);
                },

            });
Steve Wolfe
  • 59
  • 1
  • 7

1 Answers1

0

I created a new API call that has fixed the issue.

        //Load dataTable from dateFilter
     $("#dateFilterBy").change(function () {
         listInvoices($('#dateFilterBy').val())

         $.ajax({
              url: 'Controllers/Invoices/',
              data: { dateRange: $('#dateFilterBy').val() }
           })
     });

    public ActionResult Index(string dateRange)
    {
        //var searchRange = dateRange;
        string userId = User.Identity.GetUserId();
        var userAccountID = _context.AccountProfile.Single(c => c.UserId == userId);
        var invoices = _context.InvoiceMaster.Where(c => c.AccountGUID == userAccountID.AccountGUID);
        List<InvoiceMaster> myInvoiceList = invoices.ToList();


        return View(invoices);
    }
Steve Wolfe
  • 59
  • 1
  • 7