【问题标题】:Json isn't returning a result that is accessible as an arrayJson 没有返回可作为数组访问的结果
【发布时间】:2009-12-17 04:59:21
【问题描述】:

我无法从控制器方法中读取 Json 结果...

我的控制器中有这个方法:

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetCurrent()
    {
        IList<string> profile = new List<string>();
        profile.Add("-1");
        profile.Add("Test");
        profile.Add("");

        return this.Json(profile);
    }

这个 jquery ajax 帖子正在调用它:

$.post("/Profile/GetCurrent", function(profile) { profileCompleteOpen(profile); }, "json");

以及在帖子回调中调用的 javascript 函数:

function profileCompleteOpen(profile) {
   alert(profile);
   alert(profile[0]);
}

第一个警报的结果显示如下数组:

["-1","测试",""]

但第二个警报的结果显示:

[

而不是

-1

我在这里做错了什么...我已经将它与我这样做的其他时间进行了比较,它似乎完全相同。为什么它不识别它是一个数组?

谢谢,
马特

【问题讨论】:

    标签: asp.net-mvc ajax json post controller


    【解决方案1】:

    尝试通过在其上使用 eval() 将配置文件中的 json 数据转换为适当的对象。

    例子:

    var profileObject = eval('(' + profile + ')');
    

    【讨论】:

      【解决方案2】:

      嗯,我会做你想做的事情,有点不同。

      我要么返回一个完全限定的对象,然后使用它的属性;

      class MyObj
      {
        public string name{get;set;}
      }
      

      填充对象并将其作为 json 对象返回。那么你的 jquery 代码可以像任何其他对象一样访问。

      另一种方法可能是return PartialView("MyView", model);

      这会将部分视图作为 html 返回到您的页面,然后您可以将其附加到您的 html。

      【讨论】:

        【解决方案3】:

        我认为profile 的类型是字符串而不是数组。为什么?检查$.post 方法参数。也许问题就在那里。

        $.post("url", null, function(profile) { ... }, "json");
        

        【讨论】:

          猜你喜欢
          • 2017-03-09
          • 1970-01-01
          • 2017-02-17
          • 2021-08-13
          • 2013-12-16
          • 2013-09-05
          • 2022-10-05
          • 2014-07-23
          • 1970-01-01
          相关资源
          最近更新 更多