【问题标题】:When invoked with a jQuery $.ajax, what to return from the Action Method if things go ok?当使用 jQuery $.ajax 调用时,如果一切正常,从 Action 方法返回什么?
【发布时间】:2012-05-01 12:16:15
【问题描述】:

这是我的代码:

    [HttpPost]
    public ActionResult VoteChampionStrongAgainst(string championStrong, string againstChampion)
    {
        int champStrongId = int.Parse(championStrong);
        int againstChampId = int.Parse(againstChampion);

        string ip = System.Web.HttpContext.Current.Request.UserHostAddress;

        using (EfCounterPickRepository counterPickRepository = new EfCounterPickRepository())
        {
            var existingCounterPick = counterPickRepository.FindAll()
                                                           .SingleOrDefault(x => x.ChampionStrong == champStrongId && x.AgainstChampion == againstChampId);

            //Does this counterpick combination already exist?
            if (existingCounterPick != null)
            {
                //Has this user already voted?
                var existingVote = counterPickRepository.FindVoteForUser(ip, existingCounterPick.CounterPickVoteId);

                //He hasn't voted, add his vote history.
                if (existingVote == null)
                {
                    StrongCounterHistory history = new StrongCounterHistory();
                    history.IPAddress = ip;
                    history.VoteType = true;
                    history.StrongCounterPickVoteId = existingCounterPick.CounterPickVoteId;

                    counterPickRepository.AddStrongPickHistory(history);
                    counterPickRepository.SaveChanges();

                    //Add a total vote the pick.
                    existingCounterPick.TotalVotes++;
                    counterPickRepository.SaveChanges();
                }
                else
                {
                    //Will use this to display an error message.
                    //How to return an "error" that jquery understands?
                }
            }
            else //This combination doesn't exist. Create it.
            {
                //Create it....
                StrongCounterPickVote newCounterPick = new StrongCounterPickVote();
                newCounterPick.ChampionStrong = champStrongId;
                newCounterPick.AgainstChampion = againstChampId;
                newCounterPick.TotalVotes = 1;

                counterPickRepository.CreateNewCounterPick(newCounterPick);
                counterPickRepository.SaveChanges();

                //Assign a vote history for that user.
                StrongCounterHistory history = new StrongCounterHistory();
                history.IPAddress = ip;
                history.VoteType = true;
                history.StrongCounterPickVoteId = newCounterPick.CounterPickVoteId;

                counterPickRepository.AddStrongPickHistory(history);
                counterPickRepository.SaveChanges();
            }

            return View();
        }
    }

这是我的 jQuery 代码:

$(".pick .data .actions .btn-success").click(function () {
    var champStrongId = $(this).data("champstrongid");
    var againstChampId = $(this).data("againstchampid");

    $.ajax({
        type: 'POST',
        url: "/Counterpicks/VoteChampionStrongAgainst",
        data: { championStrong: champStrongId, againstChampion: againstChampId },
        success: function () {
            alert("Great success!");
        },
        error: function (e) {
            alert("Something bad happened!");
            console.log(e);
        }
    });
});

我需要从我的 ActionMethod 返回什么,以便代码执行进入 success:(如果一切正常)或 error:(如果出现问题)(例如,他已经对这个特定的计数器选择进行了投票?

【问题讨论】:

  • 看来return Json(new { success = true }); 使它正确地进入success: 路径。但是尝试return Json(new { error = true }); 并不能让它进入error: 路径。有什么想法吗?
  • @naimshaikh 链接的第二个帖子中有正确答案。
  • @SergioTapia 即使您正在创建新错误,服务器也会返回 200,因此您的 javascript ajax 调用仍然会出错。您需要发送 200 以外的东西

标签: c# jquery ajax asp.net-mvc-3 actionmethod


【解决方案1】:

Servlet 应该回答“200 OK”HTTP 响应。

不知道您的“视图”api,但 HttpServletResponse.setStatus(200) 可以在 Java 端使用。不要忘记,您可以在浏览器中手动请求 AJAX url 以查看它返回的内容..

【讨论】:

【解决方案2】:

这是我要做的一些事情......

public JsonResult VoteChampionStrongAgainst(string championStrong, string againstChampion)    {
    var success = true;

    // Do all of your data stuff

    return Json(new { success = success, error = 'Some error message'});

}

JsonResult 是返回 Json 的特殊 ActionResult。它会自动为浏览器设置正确的标题。 Json() 将使用 ASP.NET 的内置序列化程序来序列化匿名对象以返回给客户端。

然后使用您的 jQuery 代码...

$.ajax({
        type: 'POST',
        url: "/Counterpicks/VoteChampionStrongAgainst",
        data: { championStrong: champStrongId, againstChampion: againstChampId },
        success: function (json) {
            if (json.success) {
                alert("Great success!");
            }
            else if(json.error && json.error.length) {
                alert(json.error);
            }
        },
        // This error is only for responses with codes other than a 
        // 200 back from the server.
        error: function (e) {
            alert("Something bad happened!");
            console.log(e);
        }
    });

为了让错误触发,您必须使用 Response.StatusCode = (int)HttpStatusCode.BadRequest; 返回不同的响应代码

【讨论】:

  • +1,我更喜欢这种方法而不是改变响应状态码
【解决方案3】:

如果您的服务器上出现类似错误,您可以返回 500 内部服务器错误

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
return Json(new { "internal error message"});

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2011-02-20
    • 2016-06-23
    • 2012-11-20
    相关资源
    最近更新 更多