Passing localstorage to controller using Ajax

只愿长相守 提交于 2021-02-07 09:24:25

问题


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?


回答1:


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);
        }
    });
}


来源:https://stackoverflow.com/questions/30669962/passing-localstorage-to-controller-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!