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

Arm*_*men 14 c# ajax asp.net-mvc jquery

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

public ActionResult CompleteRegisteration(FormCollection formCollection)
Run Code Online (Sandbox Code Playgroud)

这是我的提交按钮点击:

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);
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

现在如何将数据传递给formcollection?

And*_*rei 35

由于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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

主要变化:

  1. 设置为POST的请求类型(此处不需要,但看起来更自然)
  2. 序列化表单而不是JSON字符串作为请求数据
  3. 删除了contentType - 我们不再发送JSON了


小智 5

尝试:

$(<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);
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)