将序列化的表单传递给Action并绑定到模型 [英] Pass serialized form to Action and bind to model

查看:82
本文介绍了将序列化的表单传递给Action并绑定到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绑定从Ajax调用接收到的模型,但这不起作用.也许有人可以帮助我?

I am trying to bind model received from Ajax call but that do not work. Maybe someone could help me?

我正在使用Ajax调用ValidateFile Action

I am calling ValidateFile Action using Ajax

 $.ajax({
                    url: '@Url.Action("ValidateFile", "Converter")',
                    data: ({ file: fileName, formData: serializedForm }),
                    type: 'POST',
                    success: function (response) {
                        if (response.result) {
                        } else {
                            RemoveFile(fileName);
                        }
                    }
                });

提琴手显示这样的查询

file=!!!SP+Design!!!.txt&formData%5BEmail%5D=tomas%40mydomain.com

我在操作中接收到的数据中填充了file参数,但formData.Email属性始终为Null

I receive data in my Action with file parameter populated but formData.Email property is always Null

[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}

我的UploadOptionModel模型

namespace PC.Models
{
    public class UploadOptionModel
    {
        public string Email { get; set; }
    }
}

我要序列化的表格

@model PC.Models.UploadOptionModel
@using (Html.BeginForm())
{
    @Html.EditorFor(p => p.Email)
}

JS序列化功能

function serializeForm() {
    var data = $("form").serializeArray();
    var formData = {};
    for (var i = 0; i < data.length; i++) {
        formData[data[i].name] = data[i].value;
    }

    return formData;
}

推荐答案

您需要对数据进行JSON编码并将内容类型设置为JSON,以便模型绑定程序可以使用JSON.所以试试这个:

You need to JSON encode the data and set the content type to JSON for the model binder to work with JSON. So try this:

$.ajax({
    url: '@Url.Action("ValidateFile", "Converter")',
    data: JSON.stringify({ file: fileName, formData: serializedForm }),
    contentType: 'application/json',
    type: 'POST',
    success: function (response) {
        if (response.result) {
        } else {
            RemoveFile(fileName);
        }
    }
});

这篇关于将序列化的表单传递给Action并绑定到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆