Kyle
Kyle

Reputation: 33691

C# Web service, how to receive JSON

I made a JSON string with jquery, and i want to send it to a C# web api controller.

This is an example of the JSON object

{"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]}

I tryed to send it with a URL like this

API/Recipe/Search?json={"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]}

With my Controller like this:

public class RecipeController : ApiController
{

    [HttpGet]
    public string Search(searchObject json)
    {
        return "Asdasd";
    }
 }

and like this

   public class RecipeController : ApiController
{

    [HttpGet]
    public string Search(string json)
    {
        searchObject search = (searchObject)JsonConvert.DeserializeObject(json);

        return "Asdasd";
    }
}

But in neither case the controller will pick it up. I am using MVC4.

Here is the Jquery i am using to make the call. apiLink is the link I posted above.

$.getJSON(apiLink, function (data) {
        var items = [];

        $.each(data, function (key, val) {
            items.push('<li id="' + key + '">' + val + '</li>');
        });

        $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
        }).appendTo('body');
    });

How do I get the controller to receive the JSON object?

Thanks

Upvotes: 4

Views: 15630

Answers (2)

Habib
Habib

Reputation: 223187

You should use POST attribute with the method, this way you will be able to post complex object to the Web API,

You may create a class for the JSON, from json to cSharp

public class SearchObject
{
    public string Name { get; set; }
    public string Type { get; set; }
    public List<string> Meals { get; set; }
    public List<string> Excludes { get; set; }
}

Then in your web api, specify the method with HttpPost attribute, Web API will take care of deserialization of json in the post to your template.

[HttpPost]
public string Search(SearchObject json)
{
    return "Asdasd";
}

You may try fiddler, for making a post request, in the request header specify type:

Content-Type:application/json

and in the request body paste your json, and Execute

Upvotes: 4

Glenn Ferrie
Glenn Ferrie

Reputation: 10380

Looks like you already got a response, but here's the code for a working solution:

Note: I used JsonResult Actions in MVC3, but the principles are the same

Controller:

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost] // requires HttpPost attribute
        public JsonResult SendData(SearchObject payload)
        {
            // do something here

            return Json(new { status = "Success" });
        }
    }

    public class SearchObject
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public List<string> Meals { get; set; }
    }

View:

@{
    ViewBag.Title = "Index";
}
<script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $.ajaxSetup({ accepts: "application/json" });
    $.ajax({
        url: '@Url.Action("SendData")', type: "POST",
        success: function (data) {
            alert(data.status); 
        },
        error: function (a, b, c) { },
        data: { 'Name':'Glenn','Type':'4','Meals':["1","2"] }
    });
</script>

<h2>Index</h2>

Hope this helps...

Upvotes: 0

Related Questions