JQuery.Ajax和MVC4

Ben*_*Ben 6 c# asp.net-mvc jquery

我需要在我的控制器上调用一个方法来使用JQuery.Ajax方法返回一个复杂类型.

 function CallMethodTest(Id) {
            //alert(Id);
            $.ajax({
                type: 'POST',
                url: '/MyController/MyMethod',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                //data: "{'Id': '" + Id + "'}",
                success: function (data) {
                    alert(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }

[System.Web.Services.WebMethod]
public string MyMethod()
{
    return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
    return "1"; // Works fine
}
Run Code Online (Sandbox Code Playgroud)

正如代码所解释的那样,如果我返回一个整数(作为字符串),则返回有效并且我警告"1",但是,如果我尝试返回任何字母字符,我会收到MyMethod注释中显示的警报.

Tim*_*mes 10

从您的代码中,您看起来好像是从Controller返回值 url: "/MyController/MyMethod"

如果要从控制器返回值,则删除[System.Web.Services.WebMethod]代码并将其替换为此代码ActionResult

[HttpPost]
public ActionResult MyMethod(){
    return Json("ABC");
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您打算在控制器中调用方法,GET则使用

public ActionResult MyMethod(){
    return Json("ABC", JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)