javascript - 使用 Ajax 将表单数据发布到 Controller 方法

标签 javascript c# ajax asp.net-mvc

问题

我想使用 AJAX 将表单数据异步发布到 Controller 。这是我的 JavaScript 的简化 View :

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

问题从服务器端开始,所有方法参数都为空。

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

问题

我的问题是,为什么所有的方法参数都是空的?

额外研究

我查看了请求流内部,从长度上可以看出那里有内容,但是出于某种原因,MVC 无法将我在 FormData 对象中指定的参数与方法中的参数相匹配 Controller 。

我为什么要这样做?

是的,我想发布数据。我已经简化了示例,但我想发布比 URL 上可以放置的更多的数据,因此 REST 方法(在查询字符串上传递数据)对于此解决方案是 Not Acceptable 。

最佳答案

尝试以这种方式进行ajax调用,我认为这是发出请求的最佳方式

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

Action 方法是

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

关于javascript - 使用 Ajax 将表单数据发布到 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858829/

相关文章:

javascript - li :hover 的简单 IE7 修复

javascript - 使用 jQuery 显示选择查询结果

javascript - 如何在正则表达式中使用变量 'object'?

javascript - 如何垂直和水平对齐一个div到页面中心

c# - 数据成员顺序和 XML 反序列化

c# - 无法从 List<DateTime?> 转换为 List<dynamic>

c# - 如何将 id 数字字符串传递给此类

javascript - angularjs http 只工作一次

javascript - 对每个带有 class/id 的 div 使用 ajax

php - 多个 mysql_connect 语句相互抵消