如何使用Javascript xmlhttprequest将Json对象(或字符串数据)发送到MVC控制器

18

我在ASP.NET MVC中创建了一个Web应用程序,并尝试通过Javascript AJAX调用控制器。在Jquery中,我们可以发送一个Json对象,MVC Model Binder会自动尝试创建一个.NET对象并将其作为参数传递给控制器。

但是我正在使用Web Workers,其中无法使用Jquery。因此,我通过原始的xmlhttprequest对象进行AJAX调用。是否有一种方法可以通过这种方法发送Json对象?

我使用了xmlhttprequest的send方法,但控制器中的模型对象为空:(


很好地使用了“vanilla”这个词 :) 我喜欢 - dyslexicanaboko
3个回答

39
你可以使用JSON2将其转换为字符串,然后在进行POST请求时设置Content-Type头为application/json

http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

你可以这样做:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Controller/Action');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(JSON.stringify(myData));

非常感谢Dve!!它在主线程上运行。现在我将尝试在工作线程上运行。将发布结果。 - ganeshran
它在工作线程上也正常运行!太棒了,感谢Darin和Dve。 - ganeshran
var myData = {}; myData.Name = 'XXX'; 变量myData = {}; myData.Name = 'XXX'; - Ziggler
这在ASP.NET MVC中有效,但在ASP.NET Core MVC应用程序中无效。有什么想法吗? - Ziggler

7
这里有一个例子。它假设你正在使用内置的JsonValueProviderFactory的ASP.NET MVC 3.0版本。如果不是这种情况,你可以看一下这篇博客文章
视图模型:
public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult SomeAction(MyViewModel model)
    {
        return Content("success", "text/plain");
    }
}

查看:

<script type="text/javascript">
    var http = new XMLHttpRequest();

    var value = '{ "prop1": "value 1", "prop2": "value 2" }';
    // It would be better to use JSON.stringify to properly generate
    // a JSON string
    /**
    var value = JSON.stringify({
        prop1: 'value 1',
        prop2: 'value 2'
    });
    **/

    http.open('POST', '/Home/SomeAction', true);
    http.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    http.setRequestHeader('Content-Length', value.length);
    http.onreadystatechange = function () {
        if (http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(value); 
</script>

非常感谢Darin,我按照你告诉我的方法尝试了一下,并在Global.asax中注册了JSonValueProviderFactory。但是,模型对象仍然具有空属性。我在JSon对象中使用了相同的属性名称,但无法将其绑定到json对象。此外,我在Firefox中发现了这个错误-不确定它是否相关错误:uncaught exception: [nsIXMLHttpRequest.setRequestHeader]" nsresult:"0x80004005 (NS_ERROR_FAILURE)" location:"JS frame :: http://localhost:6438/Scripts/script.js :: <TOP_LEVEL> :: line 40" data:no] - ganeshran

-1
使用$.Ajax(),您可以轻松地将数据从JavaScript传递到MVC中的控制器。
供参考,

var uname = 'Nikhil Prajapati'; $.ajax({

      url: "/Main/getRequestID",  // This is path of your Controller with Action Result.
      dataType: "json",           // Data Type for sending the data

      data: {                     // Data that will be passed to Controller
          'my_name': uname,     // assign data like key-value pair       
           // 'my_name'  like fields in quote is same with parameter in action Result
      },

      type: "POST",               // Type of Request
      contentType: "application/json; charset=utf-8", //Optional to specify Content Type.

      success: function (data) { // This function is executed when this request is succeed.
              alert(data);
      },

      error: function (data) {
              alert("Error");   // This function is executed when error occurred.
      }

)};

现在,在控制器端,

public ActionResult getRequestID(String my_name) {

        MYDBModel myTable = new Models.MYDBModel();
        myTable.FBUserName = my_name;
        db.MYDBModel.Add(myTable);
        db.SaveChanges();              // db object of our DbContext.cs
        //return RedirectToAction(“Index”);   // After that you can redirect to some pages…
        return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
    }

更多参考资料请访问在MVC中从JavaScript发送数据到控制器


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接