C# 如何使用ajax调用将formcollection传递给动作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17797053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:30:18  来源:igfitidea点击:

How to pass formcollection using ajax call to an action?

c#jqueryajaxasp.net-mvc

提问by Armen

I'm trying to replace a form submit with ajax call. the action needs formcollection and I don't want to create a new Model. So I need to pass the whole form (just like form submit) but through ajax call. I tried to serialize and using Json but the formcollection is empty. this is my action signature:

我正在尝试用 ajax 调用替换表单提交。该操作需要 formcollection,我不想创建新模型。所以我需要通过整个表单(就像表单提交一样)但是通过ajax调用。我尝试序列化并使用 Json,但 formcollection 为空。这是我的动作签名:

public ActionResult CompleteRegisteration(FormCollection formCollection)

and here is my submit button click:

这是我的提交按钮点击:

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);
                    }
                }
            });

now how can I pass data into formcollection?

现在如何将数据传递到 formcollection 中?

采纳答案by Andrei

Since FormCollectionis a number of key-value pairs, JSON is inappropriate data format for its representation. You should use just serialized form string:

由于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);
        }
    }
});

Key changes:

主要变化:

  1. typeof the request set to POST (not necessary here, but seems more natural)
  2. Serialized form instead of JSON string as request data
  3. contentTyperemoved - we are not sending JSON anymore
  1. 设置为 POST 的请求类型(这里不需要,但看起来更自然)
  2. 序列化形式而不是 JSON 字符串作为请求数据
  3. contentType已删除 - 我们不再发送 JSON

回答by Angry_Yodeler

Try:

尝试:

$(<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);
            }
        }
    });
});

回答by Sushil Jadhav

If anyone want to pass additional data to the FormCollection then you can try below.

如果有人想将其他数据传递给 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/>

Action Method

动作方法

public ActionResult GetUser(FormCollection frm)
  {
   int UserId = Convert.ToInt32(frm["user"]);
   // your code
   return Json(data, JsonRequestBehavior.AllowGet);
  }

Refer linkfor more details.

有关详细信息,请参阅链接