Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c# - How to pass formcollection using ajax call to an action?

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

now how can I pass data into formcollection?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Key changes:

  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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...