简体   繁体   中英

Posting form data to a controller method using Ajax

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.

try to make the ajax call this way, i think it is the best way to make request

    function SendForm() {
            var data = {};
            data.value1 = "Hello";
            data.value2 = "World";

            $.ajax({
                url: "http://server/controller/SomeAction",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8;",
                success: function (data) {
                    // your code in success
                    alert("success");
                }
            });
        }

and the action method will be

 [HttpPost]
 public JsonResult SomeAction(string value1, string value2)
 {
  if(String.IsNullOrEmpty(value1) || String.IsNullOrEmpty(value2)) 
    { 
     throw new Exception("World not found."); 
    }
     return Json("something");
 }
 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
    }
   });
 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: formData, value1: "hello", value2: "world"},
    success: function (data) {
    // ..... any success code you want
    }
  });

And Recieve JSON at server side

Please try this .I am Unable to run the code on a project now.This is the theory though ,You can pass the data seperately using AJAX

If Only value1 and value2 is reqd - Server

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

JQuery

  $.ajax({
    url: "http://server/controller/SomeAction",
    type: 'post',
    cache: false,
    contentType: false,
    processData: false,
    data: { value1: "hello", value2: "world"},
    success: function (data) {
    // ..... any success code you want
    }
  });

Try using AJAX this way,

function SendForm() {      
       $.ajax({
                type: 'POST',
                url: '/controller/SomeAction',
                data: { value1 : 'hello', value2 : 'world' },
                success: function (result) {
                    //Your success code here..
                },
                error: function (jqXHR) {                        
                    if (jqXHR.status === 200) {
                        alert("Value Not found");
                    }
                }
            });
     }

You can find the value1 and value2 to server side.

Controller

[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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM