JsonStatham
JsonStatham

Reputation: 10374

Passing localstorage to controller using Ajax

I need to access the data held in localstorage, server side but that's another story.

I have this button in my view:

<div style="float:right;">
    <input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>

This JS function:

function sendLocalStorage() {

    var JsonLocalStorageObj = JSON.stringify(localStorage);
    //var test = ["test1", "test2", "test3"];

    $.ajax({
        url: "/MyControllersName/Test",
        type: "POST",
        dataType: 'json',
        data: JsonLocalStorageObj,
        contentType: "application/json; charset=utf-8",
        beforeSend: function () { alert('sending') },
        success: function (result) {
            alert(result.Result);
            localStorage.clear();
        }
    });
};

And this test controller method:

    [HttpPost]
    [WebMethod]
    public ActionResult Test(string JsonLocalStorageObj)
    {
        string x = JsonLocalStorageObj;
        //deserialize here
        return RedirectToAction("Index");
    }

When I run JSON.stringify(localStorage); in chrome dev tools, I see data as expected, however when I debug my controller JsonLocalStorageObj is always null. As a test I used the test array that is commented out and set the parameter on the controller to accept a List<string> and this came through populated.

Whats the problem with JSON.stringify(localStorage); being passed through?

Upvotes: 2

Views: 3326

Answers (1)

Vitor Hugo Salgado
Vitor Hugo Salgado

Reputation: 141

You haven't specified the parameter name of your action (JsonLocalStorageObj) and your content and dataType were wrong too. Try change your javascript code to this:

function sendLocalStorage() {

    var JsonLocalStorageObj = JSON.stringify(localStorage);
    //var test = ["test1", "test2", "test3"];

    $.ajax({
        url: "/MyControllersName/Test",
        type: "POST",
        data: { JsonLocalStorageObj: JsonLocalStorageObj },
        success: function (result) {
            alert(result);
        }
    });
}

Upvotes: 2

Related Questions