mvc中的Ajax Post始终返回错误

时间:2015-06-22 08:10:06

标签: ajax json asp.net-mvc razor

我对Ajax帖子很新,我想知道是否有人可以帮助我解决为什么我一直收到错误消息。

VideoController

[HttpPost]
    public ActionResult Check(string userid, string streamid)
    {
        return Json(new { success = true });
    }

httppost相当空的原因只是在我开始编写代码之前测试它是否有效。

Jquery

var userID = '@User.Identity.GetUserId()';
var defaultContext = window.location.hash === "" ? XSockets.Utils.guid() : window.location.hash.substr(1);
    //alert(defaultContext);

    $.ajax({
        url: '/video/check',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            userid: userID,
            streamid: defaultContext
        }),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function (error) {
            alert(error.status);
        }
    });

我一直闯进我的error: function,如果我调试我从未点过[httpPost] Method

有人可以提供帮助

更新

我在警报中得到了404。

RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

2 个答案:

答案 0 :(得分:1)

尽量不要强调网址:

var tURL = '@Url.Action("Check", "Video")';
$.ajax({
        url: tURL ,
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            userid: userID,
            streamid: defaultContext
        }),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function () {
            alert("error");
        }
    });

答案 1 :(得分:0)

服务器:

[HttpPost]
public JsonResult Foo(string userid, string streamid)
{
    return new JsonResult{ Data = new {success = true}};
}

客户端:

$.post('/home/foo',{userid:'123', streamid:'bar'}, function(r) {
    console.log(r);
});

编辑 - 如果您更喜欢$.ajax方式而不是$。post

$.ajax({
    url: '/home/foo',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({
        userid: '123',
        streamid: 'bar'
    }),
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

令人困惑的是你将XSockets.NET与AJAX混合......当你有XSockets时,为什么要通过HTTP传递任何东西?您可以轻松地将其传递给XSockets并从那里调用您的服务层。只是一个友好的指针。