Skip to main content
 首页 » 编程设计

c#之如何从 ASP.NET MVC 4 中的 Controller 返回 JSON 对象

2024年02月13日13小虾米

当我console log 我的response 时,我得到的只是HTML。如何获取播放器对象?

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

请您参考如下方法:

您正在调用一个 ActionResult 方法,该方法将返回比您需要的 JSON 多得多的结果。

将您的代码更改为

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

您可能还需要确认在您的 JavaScript 文件中提取的 URL 是正确的。参数未正确传递或 Razor 未正确识别 @ 转义字符。