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

1
  • Good use of the word vanilla :) I like that Commented Aug 2, 2013 at 17:58

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much Dve!! It is working on the main thread. Now I am going to try on the worker thread. Will post the results
It is working on the worker thread too!! Awesome, thanks Darin and Dve.
var myData = {}; myData.Name = 'XXX';
This works in ASP.NET MVC but not in ASP.NET Core MVC application. Any ideas?
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>

1 Comment

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 :: localhost:6438/Scripts/script.js :: <TOP_LEVEL> :: line 40" data: no]
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.