Mvc:使用javascript数组从json中获取值到Mvc控制器

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

本文关键字:Mvc 获取 控制器 使用 javascript 数组 json      更新时间:2023-09-26

我需要从json结果I请求中读取每个值到控制器动作。这是我的客户端

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

Ok,现在我使用这种方式,因为我需要发送2个javascript数组,并在发现很多这种方式适合我。

这是我的服务器端。根据我如何张贴字符串数组的ASP。没有表单的。NET MVC控制器?我已经创建了这个

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