2

I have tried many different solutions from other people but have had no luck with either, and I can't seem to be able to debug javascript.

These are some of the variables just so you can see the types. All variables contain data

My view is as follows:

    var startTime = new Date();
    var images = @Html.Raw(Json.Encode(ViewBag.Images));
    var sound = @Html.Raw(Json.Encode(ViewBag.Tones));
    var gamePlayed = @Html.Raw(Json.Encode(ViewBag.GamePlayedId));


function SaveGameData()
    {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("Play", "Game")',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            data: {
                GamePlayedId: gamePlayed,
                Level: level,
                ExpectedImageName: expectedImageArray,
                ExpectedToneName: expectedToneArray,
                SelectedImageName: selectedImageArray,
                SelectedToneName:selectedToneArray,
                StartTime: startTimeArray,
                EndTime: endTimeArray
            },
            success: function () {
                alert('suc');
            },
            error: function (args) {
                alert('error');
            }
        });
    }

My controller is as follows:

    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Play(SaveGameViewModel model)
    {
        // Do something
        return Json(new { success = true , message ="successful"});
    }

My viewmodel is as follows:

public class SaveGameViewModel
{
    public int GamePlayedId { get; set; }
    public int Level { get; set; }
    public List<string> ExpectedImageName { get; set; }
    public List<string> ExpectedToneName { get; set; }
    public List<string> SelectedImageName { get; set; }
    public List<string> SelectedToneName { get; set; }
    public List<DateTime> StartTime { get; set; }
    public List<DateTime?> EndTime { get; set; }
}

I keep getting the error message from the ajax alert. I have tried many different things and nothing seems to work. I appreciate any help that you can give. Thanks a lot!

6
  • 2
    What errors do you get? Commented Jun 26, 2015 at 12:53
  • 2
    If you're using form, You just need to serialize form and pass it to the controller as your controller is having model as an argument! Commented Jun 26, 2015 at 12:56
  • You have numerous potential problems. Your method is decorated with [ValidateAntiForgeryToken] but you don't send the token. You include the contentType: "application/json; charset=utf-8", option but don't stringify the data - wither remove the option or use data: JSON.stringify({....}), You have not indicated what expectedImageArray (and the other xxxArray values are) Commented Jun 26, 2015 at 13:00
  • In whatever browser you're testing this in, there should be some network tools. Use them. Look at what you're sending across and that should help you. Or have a look at Fiddler to help you t/s this. Commented Jun 26, 2015 at 13:03
  • @StephenMuecke thank you so much! the [ValidateAntiForgeryToken] was the one causing all the issues. Once I removed that and removed the contentType I see that is is now reaching my controller. How can I imlpement the XSRF token with ajax/javascript? Commented Jun 26, 2015 at 13:54

1 Answer 1

2

There are at least 2 issues with the code your have shown.

First your method is marked with the [ValidateAntiForgeryToken] attribute but you do not pass the token so the method will never be run. Either remove the attribute, or include it using (this assumes your form includes @Html.AntiForgeryToken())

data: { 
    __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),      
    .... // your other properties
},

Second, your posting a javascript object so you need to remove the contentType: "application/json; charset=utf-8", option (or alternatively you need to stringify the data using JSON.stringify()

Side note: Its unclear from you code why you are manually constructing an object to send to the controller. If your form controls are based on SaveGameViewModel and are correctly generated using the strongly typed html helpers, then you can post it all back using

$.ajax({
    data: $('form').serialize(),
    ....
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.