我正在尝试向控制器提交一个表单,该控制器接受FormCollection作为参数。当我尝试访问dsCollection中的项时,它返回null。FormCollection中唯一的项是 "__RequestVerificationToken" 和 "dsCollection"。另外一件事是,我正在使用JavaScript动态生成表单HTML,并同时为它们分配值。
以下是我的ajax代码,用于将数据发送到服务器端:
如果我使用serializeArray()函数,会返回31个条目,但实际上这些条目是以索引从0到30的形式表示的,其格式为
以下是我的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]"
。