簡體   English   中英

將數據數組從Javascript傳遞到C#

[英]Passing data array from Javascript to C#

這是我的課程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; }

}

我的Ajax電話:

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
        });

以及接收數據的方法:

 [HttpPost]
  public ActionResult TempData(ARecipe recipe) {

     return Json("");
  }

我的Ajax調用很好地轉到了TempData方法,但是當我使用調試器分析參數“ recipe”時,我注意到所有字段均為“ null”。

為什么呢

你有解決方案嗎 ?

謝謝

您正在以JSON形式發送數據,但服務器希望將其作為常規POST數據發送。 只需讓ajax方法將其轉換為常規POST請求,而不是將其強制為JSON:

///Form data
data: dico,

只需更正這些問題:

 $.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("");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM