本文介绍了如何通过使用的FormCollection Ajax调用的动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换的形式与AJAX调用提交。该动作需要的FormCollection,我不希望创建一个新的模型。所以,我需要通过整个窗体(就像提交表单),而是通过Ajax调用。我试图序列化和使用JSON,但的FormCollection是空的。这是我的行动签名:

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:

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

现在我怎么能传递数据的FormCollection?

now how can I pass data into formcollection?

推荐答案

由于的FormCollection 是一个数字键 - 值对,JSON是其重新$不合适的数据格式p $ psentation。你应该只使用序列化形式的字符串:

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

var form = $("#onlineform").serialize();
$.ajax({
    type: 'POST'
    url: "/Register/CompleteRegisteration",
    data: form,
    dataType: 'json',
    success: function (data) {
        if (data.result == "Error") {
            alert(data.message);
        }
    }
});

主要变化:

  1. 键入设置为POST请求的(没有必要在这里,但似乎更自然)
  2. 在序列化的形式,而不是JSON字符串作为请求数据
  3. 的contentType 删除 - 我们不发送JSON了
  1. type of the request set to POST (not necessary here, but seems more natural)
  2. Serialized form instead of JSON string as request data
  3. contentType removed - we are not sending JSON anymore

这篇关于如何通过使用的FormCollection Ajax调用的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 21:57