skip to Main Content

I am trying to send an object in JSON to my controller, however, the objects properties appear to be null, and the payload is being sent, there just isn’t any data-pairing going on across the request.

I have not seen a lot of recent solutions to this, mostly from 10+ years ago, and was hoping someone can lead me to a modern solution of this problem.

I have a model:

 public class Expenses
    {
        public int Id { get; set; }
        public int Month { get; set; }
        public int Week { get; set; }
        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category category { get; set; }
        public float Amount { get; set; }
        public string Date { get; set; }
        public string Description { get; set; }
}

I create a similar object in JS

 //create the object
        let expense = {
            id: "listOrder"+listOfExpensesCounter,
            Month: formData.month,
            Week: formData.week,
            Type: category[0],
            Amount: formData.amount === "" ? 0 : formData.amount,
            Date: formData.date === "" ? getCurrentDate() : formData.date,
            Description: formData.description
        }

I then proceed with an AJAX call to the controller:

function ajaxCall(expense) {
            const obj = JSON.stringify(expense);
            $.ajax({

                url:'/Expenses/Create',

                // Type of Request
                contentType: 'application/json; charset=utf-8',
                type: "Post",
                data: obj,
                dataType: "json",

                // Function to call when to
                // request is ok 
                success: function (data) {},

                // Error handling 
                error: function (error) {}
            });
        }

My Controller:

 [HttpPost]
        public async Task<IActionResult> Create(Expenses expense)
        {
            try
            {
         
                Expenses newExpense = new Expenses
                {
                    Month = expense.Month,
                    Week = expense.Week,
                    CategoryId = expense.CategoryId,
                    Amount = expense.Amount,
                    Date = expense.Date,
                    Description = expense.Description                
                 };

                
                _db.expensesRepository.Add(newExpense);
                _db.Save();
                return this.Ok($"hello world");
            }
            catch (Exception e)
            {
                return this.Ok($"hello world error");
            }
        }

3

Answers


  1. try to add the FromBody Attribute like this

    Create([FromBody] Expenses expense)
    
    Login or Signup to reply.
  2. i think you don’t need to do JSON.stringify() you can directly pass json object

    function ajaxCall(expense) {
                $.ajax({
    
                    url:'/Expenses/Create',
                    // Type of Request
                    contentType: 'application/json; charset=utf-8',
                    type: "Post",
                    data: expense,
                    dataType: "json",
    
                    // Function to call when to
                    // request is ok 
                    success: function (data) {},
    
                    // Error handling 
                    error: function (error) {}
                });
            }
    

    Also check the upper case and lower case

    Login or Signup to reply.
  3. Seems your class that you have created doesn’t match the object you create

    public class Expenses
        {
            public int Id { get; set; }
            public int Month { get; set; }
            public int Week { get; set; }
            public int CategoryId { get; set; }
            [ForeignKey("CategoryId")]
            public Category category { get; set; }
            public float Amount { get; set; }
            public string Date { get; set; }
            public string Description { get; set; }
    }
    

    The object you create includes:

    let expense = {
                id: "listOrder"+listOfExpensesCounter,
                Month: formData.month,
                Week: formData.week,
                Type: category[0],
                Amount: formData.amount === "" ? 0 : formData.amount,
                Date: formData.date === "" ? getCurrentDate() : formData.date,
                Description: formData.description
            }
    

    The object you create is missing. CategoryId, category and you are passing a Parameter called Type which is not specified in your C# class Expenses, and assigning the value category[0] to it. Check those object attributes with your C# class accordingly.

    Ensure the property names in the JavaScript object (Id, Month, Week, CategoryId, Amount, Date, Description) match exactly with the properties in your Expenses C# model.

    Also in your Endpoint in C# make sure to add [FromBody]:

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] Expenses expense)
    {
        try
        {
            Expenses newExpense = new Expenses
            {
                Month = expense.Month,
                Week = expense.Week,
                CategoryId = expense.CategoryId,
                Amount = expense.Amount,
                Date = expense.Date,
                Description = expense.Description
            };
    
            _db.expensesRepository.Add(newExpense);
            _db.Save();
            return this.Ok("hello world");
        }
        catch (Exception e)
        {
            return this.Ok("hello world error");
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search