简体   繁体   中英

Pass object from Javascript to MVC Controller

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM