簡體   English   中英

MVC:使用JavaScript數組從JSON獲取值到MVC控制器

[英]Mvc: get values from json using javascript arrays to mvc controller

我需要從我請求給控制器操作的json結果中讀取每個值。 這是我的客戶

$.ajax({
        type: "POST",
        url: "List",
        data: { firstArray: arrayCountries, secondArray: arrayLang },
        success: function (result) {

             //here i need each value from json, but it's not working for me   
        },
        dataType: "json",
        traditional: true
    });

好的,現在我使用這種方式,因為我需要發送2個javascript數組,並且在找到很多這種方式之后對我有效。

這是我的服務器端 根據我如何將字符串數組發布到沒有表單的ASP.NET MVC Controller中? 我創建了這個。

public ActionResult List(List<String> firstArray, List<String> secondArray)
{
    //But here i need a list of sections, so i call a method for that
      var sections = SomeClass.getSections(fistArray, secondArray);

    //And return the json with the collection 
      return Json(sections, JsonRequestBehavior.AllowGet);
}

現在這是我的getSections方法

public static IEnumerable getSections(List<String> firstArray, List<String>secondArray)
{
    entities db = new entities();

    var result = from values in db.Sections
                 where ... 
                 select new SectionsModel{ // do something  };

    return result.OrderBy(p => p.Description);
}

現在,我在客戶端獲得了更好的json,但我不知道如何訪問它,如何從中獲取每個值? ... 提前致謝。

您需要先對其進行解析,然后才能像在.NET中一樣訪問屬性。

$.ajax({
        type: "POST",
        url: "List",
        data: { firstArray: arrayCountries, secondArray: arrayLang },
        success: function (result) {

             var sections = JSON.parse(result);

             // access properties here
        },
        dataType: "json",
        traditional: true
    });

暫無
暫無

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

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