Form.serialize()似乎返回null。

4
我正在尝试向控制器提交一个表单,该控制器接受FormCollection作为参数。当我尝试访问dsCollection中的项时,它返回null。FormCollection中唯一的项是 "__RequestVerificationToken" 和 "dsCollection"。另外一件事是,我正在使用JavaScript动态生成表单HTML,并同时为它们分配值。
以下是我的ajax代码,用于将数据发送到服务器端:
$(document).ready(function () {
$('#postEditDatasource').click(function (event) {
    alert(JSON.stringify(deletedDatapoints));
    //serialise and assign json data to hidden field
    $('#dsDeletedDP').val(JSON.stringify(deletedDatapoints));

    //anti forgery token
    //get the form
    var form = $('#__dsAjaxAntiForgeryForm');
    //from the form get the antiforgerytoken
    var token = $('input[name="__RequestVerificationToken"]', form).val();

    var URL = '/Settings/EditDatasource';
    console.log(form);
    //we make an ajax call to the controller on click
    //because the controller has a AntiForgeryToken attribute
    //we need to get the token from the form and pass it with the ajax call.
    $('#__dsAjaxAntiForgeryForm').on('submit', function () {
        $.ajax({
            url: URL,
            data: {
                __RequestVerificationToken: token,
                dsCollection: form.serialize()
            },
            type: 'POST',
            success: function (result) {
                alert('this worked')
                if (data.result == "Error") {
                    ShowDatasourcePostAlert('failPost', 3000);
                } else {
                    ShowDatasourcePostAlert('successPost', 3000);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR + ', ' + textStatus + ', ' + errorThrown);
            }
        })
        return false;
    })
});
})

这是我的控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditDatasource(FormCollection dsCollection)
    {
        var devName = dsCollection["deviceName"];
            //LoadDataToViewModel();

            //Get the name of the device in which we will pass it to the XML edit helper 
            //In order for us to locate the
            //var getEditDatasource = Convert.ToString((from ds in dsVM.devices
            //                         where ds.deviceID == Convert.ToInt64(dsCollection["dsID"])
            //                         select ds.deviceName));


            return new EmptyResult();
    }

这是我的HTML代码片段,其中有很多控件,但它们基本上都遵循相同的格式。

    <div class="form-group">
<label class="col-md-2 control-label" for="deviceName">Device Name: </label>
<div class="col-md-10">
<input id="deviceName" class="form-control" type="text" data-val="true" data-val-required="Device name is required" name="deviceName" value="TestName">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="deviceDisplay">Displayed As: </label>
<div class="col-md-10">
<input id="deviceDisplay" class="form-control" type="text" data-val="false" data-val-required="Device name is required" name="deviceDisplay" value="testDisplay">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="deviceDesc">Description: </label>
<div class="col-md-10">
<textarea id="deviceDesc" class="form-control" data-val="false" name="deviceDesc">Test desc</textarea>
</div>
</div>

如果我使用serializeArray()函数,会返回31个条目,但实际上这些条目是以索引从0到30的形式表示的,其格式为"dsCollection[0][name]" "dsCollection[0][value]"

你尝试过使用:https://api.jquery.com/serializeArray/ 吗? - Jeff
你有一行代码写着console.log(form); 这个结果是null吗? - Luis.Andrade
@Luis.Andrade 不是空的。 - Johnathon64
@Johnathon64 嗯,有些事情正在发生,我不确定是什么,我不是专家,但我会尽力帮忙。我建议你使用这个链接助手,因为如果你有一个模型,它将为你编写ajax调用,我认为你可以将令牌作为参数发送。 - Luis.Andrade
1个回答

5

serialize方法将您的form字段转换为查询字符串,因此您应该只需将令牌附加到该字符串而不是创建另一个对象。

如果您检查今天的请求,您会看到您正在发布像这样的值:

_RequestVerificationToken=token&dsCollection=deviceDesc%3Dcontent1%26deviceDisplay%3Dcontent2

当您在标准表单中使用防伪标记时,标记数据将与其他输入数据一起发送(因为实际上它只是一个隐藏的输入),因此发送它的正确方式如下:

deviceDesc=content1&deviceDisplay=content2&_RequestVerificationToken=token

另一个问题是,你的防伪标记似乎已经在你的 form 中了,所以你不需要做任何事情,只需使用form.serialize即可。

你可以在你的 Javascript 代码中执行以下操作:

data: form.serialize()

序列化是否也包括隐藏输入字段?在我的集合中,当我逐步执行C#代码时,它们似乎没有被包括进去。 - Johnathon64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接