jquery - 如何将serializeArray作为json传递给MVC Controller

标签 jquery asp.net-mvc json

我有一个表单,我想将其数据传递到我的 Controller 。这是我正在进行的 JQuery 调用 -

    var data = $form.serializeArray();

    var options = {

        contentType: "application/json",
        url: "/Form/Save",
        data: JSON.stringify(data),
        type: "post",
        datatype: "html",
        success: function (result, xhr, status) {
            console.log(result);
        },
        error: function (xhr, status, error) {
            // redirect to error page
        }
    };

    $.ajax(options);

这就是我在 Controller 中接收此信息的方式 -

    public ActionResult Save(string paramJson)
    {
        // save paramJson

        return null;
    }

但是我在“保存”操作中收到的只是 paramJson = null。我也在下面尝试过 -

数据:JSON.stringify({paramJson: data})

但是没有成功。这里应该做什么?

最佳答案

我从上面的答案中得到了一些提示,并能够制定一个非常适合我的解决方案。我现在收到格式为 formname: formvalue 的 json,而不是 name: formname, value: formvalue 格式。这是 -

    var json = {};

    // converting to formname:formvalue format
    $.each($form.serializeArray(), function (i, field) {
        json[field.name] = field.value || '';
    });

    // stringify the parameter
    var data = { paramJson: JSON.stringify(json) };

    var options = {

        contentType: "application/json",
        url: "/Form/Save",
        data: JSON.stringify(data),
        type: "post",
        datatype: "html",
        success: function (result, xhr, status) {
            console.log(result);
        },
        error: function (xhr, status, error) {
            // redirect to error page
        }
    };

    $.ajax(options);

关于jquery - 如何将serializeArray作为json传递给MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27317068/

相关文章:

asp.net-mvc - MVC 中的打印页面功能

.net - EF在父删除时将外键设置为空

php - 使用 jQuery/JS 读取 JSON 数组

javascript - 使用 jQuery 向 div 添加一些 HTML

asp.net-mvc - jquery中如何刷新div的内容?

html - 仅适用于 Aspnet CSS 和脚本的响应式 NavBar 下拉菜单

json - 当 json 中的字段不总是相同时的 Avro 架构

javascript - jQuery 无法从 PHP 脚本读取 JSON 响应

javascript - 如何使用某个 src url 查找 img 并使用 vanilla javascript 更改 css?

javascript - PHP 表单提交无需重新加载