简体   繁体   English

将对象从 Javascript 传递到 MVC 控制器

[英]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.我尝试了其他人的许多不同解决方案,但都没有运气,而且我似乎无法调试 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.我不断收到来自 ajax 警报的错误消息。 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.您显示的代码至少有 2 个问题。

First your method is marked with the [ValidateAntiForgeryToken] attribute but you do not pass the token so the method will never be run.首先,您的方法用[ValidateAntiForgeryToken]属性标记,但您没有传递令牌,因此该方法将永远不会运行。 Either remove the attribute, or include it using (this assumes your form includes @Html.AntiForgeryToken() )删除该属性,或使用它包含它(假设您的表单包含@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()其次,您发布了一个 javascript 对象,因此您需要删除contentType: "application/json; charset=utf-8",选项(或者您需要使用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如果您的表单控件基于SaveGameViewModel并且使用强类型 html 助手正确生成,那么您可以使用

$.ajax({
    data: $('form').serialize(),
    ....
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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