简体   繁体   中英

Trouble sending JSON data to asp.net MVC controller

In ASP.NET MVC 3 I am not having any luck trying to send JSON data to my controller.

I loop through a list and generate JSON objects from the elements and then send them off along with my query parameter:

$.each(addedIngredients.find('li'), function () {
    ingredients[count] = {
        ID: $(this).attr('id').split('_')[1],
        Name: $(this).attr('id').split('_')[0]
    };
    count++;
});

request = $.ajax({
    url: '/Ingredients/SearchIngredients',
    data: {
        q: q,
        ingredients: ingredients
    },
    dataType: 'json',
    type: 'POST',
    success: function (result) {
             //Code omitted
    },
    error: function () {
             //Code omitted
    }
});

At the controller I have

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult SearchIngredients(string q, JSONIngredient[] ingredients)
    {
        //Initialise model
        List<JSONIngredient> model = new List<JSONIngredient>();

        //Add items to list
        ir.GetIngredients(q).ToList().ForEach(i => model.Add(new JSONIngredient(i)));

        //Return model as JSON object
        return this.Json(model);
    }

Where JSONingredient is

public class JSONIngredient
{
    public int ID { get; set; }

    public string Name { get; set; }

    public JSONIngredient()
    {
    }

    public JSONIngredient(Ingredient Ingredient)
    {
        this.ID = Ingredient.ID;
        this.Name = Ingredient.Name;
    }
}

Which I made up because I thought my normal model which has additional properties which are not in the JSON was causing the problem, but I would have thought that if it did work it would have worked with my normal model...

I'm thinking that maybe the format in which I am sending the data is not correct. Examining the request in firefox show:

Parametersapplication/x-www-form-urlencoded ingredients[0][ID] 4 ingredients[0][Name] Water q sug

Source

q=sug&ingredients%5B0%5D%5BName%5D=Water&ingredients%5B0%5D%5BID%5D=4

Any help would be much appreciated.

After fiddling around with this for a while and trying this and that I finally got it to work. As I suspected the data format was incorrect. Instead of sending a pure JSON object

data: {
    q: q,
    ingredients: ingredients
}

I needed to send a stringified object:

JSON.stringify({ q: q, ingredients: ingredients})

Simple when you know it.

Call JSON.stringify around your data. See here for an example: Post an Array of Objects via JSON to ASP.Net MVC3

Try first with just 'q', then try as just 'ingredients'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM