Sitecore MVC Ajax POST to Controller

There are a few good posts that deal with posting data to a controller in Sitecore MVC. (See here.)

However I couldn't find much to do with AJAX.

If you want to make an AJAX post to a Sitecore Controller use the following code:

$(function () {

    $(".my-action-invoker").click(function () {
    var my-data = $(this).find(".my-data").html();

    $.ajax({
        url: window.location.href,
        type: "POST",
        context: this,
        data: { scController: "MyController", scAction: "MyAction", myData: my-data },
        success: function (data) {
            // do stuff
        },
        error: function (data) {
            console.log("error", data);
        }
        });
    });
});

And your controller:

[HttpPost]
public JsonResult MyAction(string myData)
{
    return Json(...)
}
comments powered by Disqus

Dave Leigh

Web, and long time Sitecore developer based in Bristol, UK, working at True Clarity - trueclarity.co.uk - @technologytalks - Minion.
I occasionally do other things too.