2014-04-23 136 views
1

当我I console log my response我回来的是HTML。我如何获得player object如何从ASP.NET MVC 4中的控制器返回JSON对象?

Site.JS:

$(".AddToPreRank").click(function (e) { 
    e.preventDefault(); 
    //grab id 
    var id = $(this).get(0).id; 
    //append player to prerank list 
    $.ajax({ 
     url: '@Url.Action("AddToPreRank")', 
     type: 'POST', 
     data: { id : id }, 
     success: function (response) { 
      console.log(response); 
      alert("hello"); 
     } 

    }); 
}); 

LeagueController.cs:

[HttpPost] 
public ActionResult AddToPreRank(int id){ 
    Player player= new Player(); 
    player = db.Players.Find(id); 
    return Json(player); 
} 

回答

3

您正在调用ActionResult方法,该方法将返回比您之后的JSON更多的方法。

更改您的代码

public JsonResult AddToPreRank(int id){ 
     Player player= new Player(); 
     player = db.Players.Find(id); 

     return Json(player); 
    } 

您可能还需要确认该URL被拾起你的JavaScript文件是正确的。无论是参数传递不正确还是Razor无法正确识别@转义字符。

+0

感谢您的回复。我仍然得到相同的结果。我也很好奇为什么我不能在调试模式下运行以查看Id是否实际传递给了控制器。当我设置断点时,什么都不会发生。 – user3562751

+0

你使用[http://getglimpse.com](掠影)?在浏览器的调试控制台中,你看到了什么Controller/Action方法被调用?你在HTML中看到什么内容被返回?这是一个普通的网页还是那里有奇怪的/错误的内容? –

+0

我使用铬。我不知道在哪里寻找被调用的Controller/Action方法。被返回的HTML是发生按钮点击的页面。 – user3562751

0

尝试使用.post的$默认返回的JSON。

$.post('@Url.Action("AddToPreRank")', data: { id : id }, 
    function (response) { 
     console.log(response); 
     alert("hello"); 
    } 
}); 

另外,返回一个JsonResult而不是ActionResult并返回玩家作为匿名类型。

[HttpPost] 
public ActionResult AddToPreRank(int id){ 
    Player player= new Player(); 
    player = db.Players.Find(id); 

    return Json(new {player}); 
} 
+0

感谢您的回复。我试过这个,并且仍然得到相同的结果。 – user3562751

0

您可以在Web环境中使用System.Runtime.Serialization.Json,或者在winform环境中使用Newtonsoft.Json(http://json.codeplex.com/)来解决您的问题。

相关问题