0

Here's my code:

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

Here's my jQuery code:

$(".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);
        }
    });
});

What do I need to return from my ActionMethod so the code execution enters success: if things went OK, or error: if things go wrong (for example, he already voted on this particular counter pick?

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257
  • It seems `return Json(new { success = true });` makes it go into the `success:` path correctly. But trying `return Json(new { error = true });` doesn't make it go into the `error:` path. Any ideas? – Only Bolivian Here May 01 '12 at 03:43
  • Try this post.. http://stackoverflow.com/questions/5867706/ajax-call-results-in-error-instead-of-succes – naim shaikh May 01 '12 at 03:54
  • Or this one... http://stackoverflow.com/questions/6010368/how-does-json-determine-a-success-from-an-error – naim shaikh May 01 '12 at 03:54
  • The second post linked by @naimshaikh has the correct answer in it. – Domenic May 01 '12 at 03:56
  • @SergioTapia even if error you are creating new error, server is returning 200 so still error on you javascript ajax call won't get hit. You need to send something other than 200 – zero7 May 01 '12 at 04:04
  • @zero7: That's great makes sense, but I need to know how to do this on the server side (MVC3). If I find an answer I'll post it I guess. – Only Bolivian Here May 01 '12 at 04:08
  • @SergioTapia take a look at my answer, that worked for me – zero7 May 01 '12 at 04:19

3 Answers3

0

Servlet should answer a "200 OK" HTTP response.

Don't know about your 'View' api, but HttpServletResponse.setStatus(200) would do on the Java side. Don't forget, you can request the AJAX url manually in your browser to see what it is returning..

Thomas W
  • 13,940
  • 4
  • 58
  • 76
0

Here's some things I'd do...

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

}

The JsonResult is a special ActionResult for returning Json. It automatically sets the correct headers for the browser. The Json() will use ASP.NET's built in serializer to serialize an anonymous object to return to the client.

Then with your jQuery code...

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

In order to have the error fire you'd have to return a different response code with Response.StatusCode = (int)HttpStatusCode.BadRequest;

jcreamer898
  • 8,109
  • 5
  • 41
  • 56
0

You can return 500 internal server error if there are any errors on your server something like

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
return Json(new { "internal error message"});
zero7
  • 1,298
  • 8
  • 14