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

后端 未结 3 1908
别跟我提以往
别跟我提以往 2020-12-16 13:28

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

相关标签:
3条回答
  • 2020-12-16 13:37

    You should just be able to use JSON2 to stringify it and set the Content-Type header to application/json when you do the post.

    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));
    
    0 讨论(0)
  • 2020-12-16 14:00

    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.

    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>
    
    0 讨论(0)
  • 2020-12-16 14:01

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

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

    )};

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

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

    0 讨论(0)
提交回复
热议问题