Bladerider1
Bladerider1

Reputation: 53

Posting json string to c# mvc method

I have a json string (json representation of a javascript array), which I want to pass to a C# controller method. However, I am either seeing the c# method parameter as null or the breakpoint not being hit.

Here is the js code:

        $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data:  { "json": JSON.stringify(selectedItems) }

        })

Where "seleteditems" is just a javascript colleciton.

My c# code is:

    [HttpPost]
    public void PersistSelections([FromBody] string json)
    {

    }

However, this is likely not the right way of doing this? I am always seeing the json parameter is null.

Any tips appreciated!

Upvotes: 2

Views: 820

Answers (2)

Nkosi
Nkosi

Reputation: 246998

A better approach would be to take advantage of the model binding instead of trying to post and parse the JSON yourself.

Create a model of the items to be sent

public class ItemModel {
    //...include the desired properties

    public string Description { get; set; }
    public string Name { get; set; }
    public decimal TotalPrice { get; set; }

    //...
}

next update the action to expect the items

[HttpPost]
public IActionResult PersistSelections([FromBody] ItemModel[] items) {
    //access posted items
}

and lastly update the client to post the json data

$.ajax({
    url: "/Home/PersistSelections",
    type: 'post',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data:  JSON.stringify(selectedItems)
})

The framework's built in model binder should parse and bind the posted JSON and populate the objects in the controller

Upvotes: 1

Roshan Srivastava
Roshan Srivastava

Reputation: 476

Since you are using contentType as application/json that's why default modelbinder is not working. if you want to fix the issue create a class let say model

  Public Class MyModel{
    Public string Json {get;set;}
   }

And in controller use

[HttpPost]
    public void PersistSelections(MyModel model)
    {

    }

Upvotes: 0

Related Questions