2

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

You said, 'A better approach would be to take advantage of the model binding instead of trying to post and parse the JSON yourself'. I get this but I have a controller method which takes different types of Json strings. In this case, I can't bind to any specific model. How to receive this data in controller? As in, what type of controller method param I should be using for this? Is there any generic type that I can use?
0

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)
    {

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.