Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 25924  / 8 Years ago, tue, march 8, 2016, 12:00:00

THE PROBLEM



I want to post form data to a controller asynchronously using AJAX. Here's a simplified view of my JavaScript:



function SendForm() {
var formData = new FormData();
formData.append('value1', 'hello');
formData.append('value2', 'world');
var xhr = new XMLHttpRequest();
xhr.upload.onload = function() {
// stuff that happens on the callback
};
xhr.open('POST', 'http://server/controller/SomeAction', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);
}


The problem begins on the server side where all the method parameters are null.



[HttpPost]
public ContentResult SomeAction(string value1, string value2)
{
if(String.IsNullOrEmpty(value1) || String.IsNullOrEmpty(value2)) { throw new Exception(World not found.); }
return Content(something);
}


THE QUESTION



My question is, why are all the method parameters null?



EXTRA RESEARCH



I've looked inside the request stream, and I can see from the length that there is content there, but for whatever reason MVC has failed to match the parameters I specified in the FormData object to the parameters in the methed in the controller.



WHY AM I DOING THIS?



Yes, I want to POST the data. I've simplified the example, but I want to post more data than can be placed on a URL, so a REST method (passing the data on the querystring) is not acceptable for this solution.


More From » c#

 Answers
89
 function SendForm() {
var formData = new FormData();
formData.append('value1', 'hello');
formData.append('value2', 'world');
$.ajax({
url: http://server/controller/SomeAction,
type: 'post',
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (data) {
// ..... any success code you want
}
});

[#63016] Friday, March 4, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kadinl

Total Points: 321
Total Questions: 117
Total Answers: 103

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;