magos
magos

Reputation: 3511

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 http://www.xul.fr/XMLHttpRequest-object.html I've read that it has to be string.

My client-side:

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

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

My server-side:

[HttpPost]
    public JsonResult SaveDataInDB(string data1, string data2) 
    {
        var dbobj = new DbObj
        {                
            field1 = data1,
            field2 = data2
        };

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


        db.DbObj.Add(dbobj);
        db.SaveChanges();

        return Json(true);
    }

Upvotes: 0

Views: 3310

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

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";

    request.open('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) {
            alert(request.responseText);
        }
    }
    request.send(JSON.stringify(o));
</script>

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

Upvotes: 1

Related Questions