【问题标题】:How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller如何将 Json 对象(或字符串数​​据)从 Javascript xmlhttprequest 发送到 MVC 控制器
【发布时间】:2011-08-28 16:22:29
【问题描述】:

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

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

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

【问题讨论】:

  • 香草这个词很好用:)我喜欢这个

标签: javascript asp.net asp.net-mvc xmlhttprequest


【解决方案1】:

您应该能够使用 JSON2 对其进行字符串化,并在发布帖子时将 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!它正在主线程上工作。现在我要尝试工作线程。将发布结果
  • 它也在工作线程上工作!!太棒了,谢谢 Darin 和 Dve。
  • var myData = {}; myData.Name = 'XXX';
  • 这适用于 ASP.NET MVC,但不适用于 ASP.NET Core MVC 应用程序。有什么想法吗?
【解决方案2】:

这是一个例子。它假定您正在使用具有内置 JsonValueProviderFactory 的 ASP.NET MVC 3.0。如果这不是您的情况,您可以查看this blog post

查看模型:

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 中发现了这个错误 - 不确定它是否相关错误:未捕获的异常:[nsIXMLHttpRequest.setRequestHeader]" nsresult:"0x80004005 (NS_ERROR_FAILURE)" location:"JS frame :: localhost:6438/Scripts/script.js :: :: line 40" 数据:无]
【解决方案3】:

使用$.Ajax(),你可以很容易的从javascript获取数据到MVC中的Controller。

供参考,

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

更多参考.. 只是访问.. Send Data from Java Script to Controller in MVC

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 2021-03-17
    • 2017-04-25
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多