0

I have the following javascript function which posts data to my controller (asp .net core 3.1 project):

function saveState() {
        const gridInstance = $("#ClaimsGrid").dxDataGrid("instance");
        var userstate = gridInstance.state();
        var data = { StateTypeID: 1, StateChange: userstate };
        $.ajax({
            type: "POST",
            data: JSON.stringify(data),
            url: "/api/PostUserState",
            contentType: "application/json",
            success: function () {
                alert("Your grid profile has been saved");
            },
            error: function () {
                alert("An error occurred during save of your grid profile");
            }
        });
    }

My controller is looking for the model UserStateChange which is defined as:

 public class UserStateChange
    {
        public int StateTypeID { get; set; }
        public string StateChange { get; set; }
    }

The controller code itself is:


        [HttpPost("/api/PostUserState")]
        public bool PostUserState([FromBody] UserStateChange state)
        {
            var UserID = new Guid(HttpContext.Session.GetString("UserId").ToString());
            UserState mod = new UserState();

            var cur = _context.UserState.First(a => a.AppUserID == UserID && a.StateTypeID == state.StateTypeID);

            //... more logic here


            return true;
        }

I'm getting the JSOn.Stringify data correctly in the javascript, but I get a 400 error and never even hit my breakpoint on the controller. What am I doing wrong, why am I getting a 400 error? Why isn't it recognizing my json model correctly?

nonesuch
  • 167
  • 3
  • 16
  • 1
    What happens if you just use `data: data` instead of JSON-stringify-ing it? – David Aug 12 '20 at 15:32
  • Does this answer your question? [When to use JSON.stringify() in an ajax call](https://stackoverflow.com/questions/40730233/when-to-use-json-stringify-in-an-ajax-call) – Roar S. Aug 12 '20 at 15:47
  • Same thing happens if I remove the JSON.stringify, it gets a 400 error. – nonesuch Aug 12 '20 at 16:07
  • What's the type of `userstate `, can you show us the ajax request payload. – mj1313 Aug 13 '20 at 08:41

1 Answers1

0

I think the problem is on the client-side, especially on the data part. Make an object in js and send it.

Yogi_Bear
  • 512
  • 2
  • 10
  • 24
  • That's what I'm doing, isn't it? – nonesuch Aug 12 '20 at 16:03
  • 1
    @Yogi_Bear is right; you need to check what you are sending to your controller. Please start with verifiying that your controller is working with Postman. Then take a look at this link, and you will see that your payload is wrong. https://stackoverflow.com/questions/40730233/when-to-use-json-stringify-in-an-ajax-call – Roar S. Aug 12 '20 at 17:38