C# 如何使用ajax调用将formcollection传递给操作?
我试图用ajax调用替换表单提交。该操作需要formcollection,我不想创建新模型。所以我需要通过ajax调用传递整个表单(就像表单提交一样)。 我试图序列化并使用Json,但formcollection是空的。 这是我的行动签名:C# 如何使用ajax调用将formcollection传递给操作?,c#,jquery,ajax,asp.net-mvc,C#,Jquery,Ajax,Asp.net Mvc,我试图用ajax调用替换表单提交。该操作需要formcollection,我不想创建新模型。所以我需要通过ajax调用传递整个表单(就像表单提交一样)。 我试图序列化并使用Json,但formcollection是空的。 这是我的行动签名: public ActionResult CompleteRegisteration(FormCollection formCollection) 这是我的提交按钮单击: var form = $("#onlineform").serialize();
public ActionResult CompleteRegisteration(FormCollection formCollection)
这是我的提交按钮单击:
var form = $("#onlineform").serialize();
$.ajax({
url: "/Register/CompleteRegisteration",
datatype: 'json',
data: JSON.stringify(form),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.result == "Error") {
alert(data.message);
}
}
});
现在如何将数据传递到formcollection 试试看:
$(<your form>).on('submit',function(){
$.ajax({
url: "/Register/CompleteRegisteration" + $(this).serialize(),
// place the serialized inputs in the ajax call
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.result == "Error") {
alert(data.message);
}
}
});
});
$()。在('submit',函数()上{
$.ajax({
url:“/Register/CompleteRegistration”+$(this).serialize(),
//将序列化的输入放入ajax调用中
数据类型:“json”,
contentType:“应用程序/json;字符集=utf-8”,
成功:功能(数据){
如果(data.result==“Error”){
警报(数据、消息);
}
}
});
});
由于FormCollection
是许多键值对,因此JSON对于其表示是不合适的数据格式。您应该使用刚刚序列化的表单字符串:
var form = $("#onlineform").serialize();
$.ajax({
type: 'POST',
url: "/Register/CompleteRegisteration",
data: form,
dataType: 'json',
success: function (data) {
if (data.result == "Error") {
alert(data.message);
}
}
});
主要变化:
如果有人想向FormCollection传递其他数据,那么您可以尝试下面的方法
<script type="text/javascript">
function SubmitInfo()
{
var id = $("#txtid").val();
var formData = $('#yourformname').serializeObject();
$.extend(formData, { 'User': id }); //Send Additional data
$.ajax({
url: 'Controlle/GetUser',
cache: false,
type: 'POST',
dataType: 'json',
data: decodeURIComponent($.param(formData)),
success: function (data) {
$('#resultarea').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<script/>
有关详细信息。谢谢。将ajax调用附加到submit是关键!在类型:“POST”行之后应该有“,”
public ActionResult GetUser(FormCollection frm)
{
int UserId = Convert.ToInt32(frm["user"]);
// your code
return Json(data, JsonRequestBehavior.AllowGet);
}