2009-12-17 40 views
0

我有麻烦读一个JSON结果从控制器的方法回一个数组访问...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阿贾克斯后叫:

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

以及JavaScript函数呼吁后的回调:

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

第一警报的结果表明,该阵列是这样的:

[ “-1”, “测试”, “”]

但第二类提醒显示了结果这样的:

[

而非

-1

什么我错在这里做什么......我也比其他时代的一个我这样做,它似乎是完全一样的。为什么不认识它是一个数组?

谢谢
马特

回答

1

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

例子:

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

完美工作,谢谢! – Matt 2009-12-18 00:37:49

0

嗯,我会做你想要做一些不同的东西。

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

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

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

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

,将返回的局部视图为html回你的页面,然后可以添加到您的HTML。

0

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

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