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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6055714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:03:39  来源:igfitidea点击:

How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller

javascriptasp.netasp.net-mvcxmlhttprequest

提问by ganeshran

I created a web application in ASP.NET MVC and trying to call a controller through Javascript AJAX. In Jquery we can send a json object which MVC Model Binder automatically tries to create a .NET object and pass in the controller as an argument.

我在 ASP.NET MVC 中创建了一个 Web 应用程序,并尝试通过 Javascript AJAX 调用控制器。在 Jquery 中,我们可以发送一个 json 对象,MVC 模型绑定器会自动尝试创建一个 .NET 对象,并将控制器作为参数传入。

However I am using a web workers in which jquery cannot be used. So I am making the AJAX call through the vanilla xmlhttprequest object. Is there a a way to send the Json object through this method?

但是,我正在使用无法使用 jquery 的网络工作者。所以我通过 vanilla xmlhttprequest 对象进行 AJAX 调用。有没有办法通过这种方法发送 Json 对象?

I used the xmlhttprequest's send method but the model object comes as null in the controller :(

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

回答by Dve

You should just be able to use JSON2 to stringify it and set the Content-Typeheader to application/jsonwhen you do the post.

您应该能够使用 JSON2 对其进行字符串化,并在您发布帖子时将Content-Type标题设置为application/json

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

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

You would do something like:

你会做这样的事情:

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

回答by Darin Dimitrov

Here's an example. It assumes that you are using ASP.NET MVC 3.0 which has a built-in JsonValueProviderFactory. If this is not your case you could take a look at this blog post.

这是一个例子。它假设您使用的是 ASP.NET MVC 3.0,它具有内置的JsonValueProviderFactory. 如果这不是你的情况,你可以看看这篇博文

View model:

查看型号:

public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

Controller:

控制器:

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

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

View:

看法:

<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>

回答by Nikhil Prajapati

Using $.Ajax(), you can easily got the data from javascript to Controller in MVC.

使用$.Ajax(),您可以轻松地将数据从javascript 获取到MVC 中的Controller。

For Reference,

以供参考,

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.
      }

)};

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.
      }

)};

and, Now At the Controller Side,

并且,现在在控制器端,

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.
    }

公共 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.
    }

For more reference.. just visit.. Send Data from Java Script to Controller in MVC

有关更多参考.. 只需访问.. 在 MVC 中将数据从 Java 脚本发送到控制器