magos magos - 1 year ago 55
Ajax Question

How to receive data from ajax send() method in a controller

I'm trying to serve the data in the ASP.NET MVC controller sent by ajax POST. On client side I use traditional XMLHttpRequest object and send() method instead of jQuery.ajax().

Do you know how to get variables from send() in controller? In documentation I've read that it has to be string.

My client-side:

var data1 = "some string";
var data2 = "other string";

var xhr = new XMLHttpRequest();"POST", "https://localhost:44301/Home/SaveDataInDB", true);
xhr.send(data1, data2);
xhr.onreadystatechange = saved;

My server-side:

public JsonResult SaveDataInDB(string data1, string data2)
var dbobj = new DbObj
field1 = data1,
field2 = data2

if (User.Identity.IsAuthenticated)
dbobj.user = User.Identity.Name;
dbobj.user = "anonymous";


return Json(true);

Answer Source

You can do like this, lets say this is your xmlHttpRequest -

<script type="text/javascript">
    var request = new XMLHttpRequest();
    var o = new Object();
    o.data1 = "Rami";
    o.data2 = "Ramilu";'POST', '/Home/xhr', true);
    request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    request.setRequestHeader('Content-Length', JSON.stringify(o).length);
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {

On the server side, have a ViewModel defined this way -

public class XhrViewModel
    public string data1 { get; set; }
    public string data2 { get; set; }

Then your controller action which want to get this data -

    public ActionResult xhr(XhrViewModel model)
        return Content("success", "text/plain");

And the output would be -

enter image description here