简体   繁体   中英

Passing data array from Javascript to C#

This is my class ARecipe :

public class ARecipe
{
    public string picture { get; set; }
    public string title { get; set; }
    public int cookingTime { get; set; }
    public int preparationTime { get; set; }
    public string IngredientList { get; set; }
    public string ingredientsDescription { get; set; }
    public int nbPersons { get; set; }
    public string Category { get; set; }
    public string difficulty { get; set; }
    public double nbStars { get; set; }

}

My Ajax call :

var dico = { 
            picture: $("#fakeInput").val(),
            title : $("#title").val(),
            cookingTime : $("#cookingTime").val(),
            preparationTime : $("#preparationTime").val(),
            IngredientList : $("#ingredientListArea").val(),
            ingredientsDescription : $("#preparationArea").val(),
            nbPersons : parseInt($("#select-nb-Persons").val()),
            Category : $("#select-category").val(),
            difficulty: $("#select-difficulty").val(),
            nbStars : 4
        };

        $.ajax({
            url: "/AddRecipe/TempData",
            type: 'POST',
            success: function (e) {
                //success event
            },
            ///Form data
            data: JSON.stringify(dico),
            ///Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false
        });

And the method receiving the datas :

 [HttpPost]
  public ActionResult TempData(ARecipe recipe) {

     return Json("");
  }

My Ajax call well go to the TempData method but when I analyse the parameter 'recipe' with the debugger, I notice that all the fields are 'null'.

Why ?

Do you have a solution ?

Thank you

You are sending the data as JSON, but the server expects is as regular POST data. Just let the ajax method turn it into a regular POST request instead of forcing it into JSON:

///Form data
data: dico,

Just Correct these issues :

 $.ajax({
        url: "/AddRecipe/TempData",
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        success: function (e) {
            //success event
        },
        ///Form data
        data: JSON.stringify(dico),
        ///Options to tell JQuery not to process data or worry about content-type
        cache: false,
    });

 [HttpPost]
 public JsonResult TempData(ARecipe recipe) {

 return Json("");
}

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