18

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.

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?

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

ganeshran
  • 3,512
  • 7
  • 41
  • 69

3 Answers3

39

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));
Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
David
  • 8,340
  • 7
  • 49
  • 71
7

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>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks very much Darin - I tried exact same method as you told and also registered the JSonValueProviderFactory in Global.asax. however the model object still has null properties. I used same property names in JSon object as well but its not able to bind it to a json object. Also I found this error in Firefox - not sure if its relavent Error: uncaught exception: [nsIXMLHttpRequest.setRequestHeader]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:6438/Scripts/script.js :: :: line 40" data: no] – ganeshran May 19 '11 at 09:35
-1

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

Nikhil Prajapati
  • 944
  • 1
  • 12
  • 30