使用Ajax将localstorage传递给控制器

时间:2015-06-05 15:10:22

标签: javascript ajax asp.net-mvc

我需要访问localstorage,服务器端保存的数据,但这是另一个故事。

我的观点中有这个按钮:

SELECT u.USER_NAME As [User]
  , COUNT(ad.ACTIVITY_ID) As [Total Activities Late]
  , SUM(CASE WHEN ad.DAYS_LATE BETWEEN 1 and 7 THEN 1 ELSE 0 END) As [Upto One Week Late]
  FROM USERS u
  JOIN ACTIVITY_DATA ad
    ON u.USER_ID = ad.USER_ID
  WHERE ad.DAYS_LATE > 0 AND ad.COMPLETED_DATE is NULL
  GROUP BY u.USER_NAME

这个JS函数:

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

这个测试控制器方法:

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

当我在chrome dev工具中运行 [HttpPost] [WebMethod] public ActionResult Test(string JsonLocalStorageObj) { string x = JsonLocalStorageObj; //deserialize here return RedirectToAction("Index"); } 时,我会看到预期的数据,但是当我调试控制器时JSON.stringify(localStorage);总是JsonLocalStorageObj。作为测试,我使用了已注释掉的测试数组,并在控制器上设置参数以接受null,这是通过填充来实现的。

问题是List<string>被传递了吗?

1 个答案:

答案 0 :(得分:2)

您尚未指定操作的参数名称(JsonLocalStorageObj),您的内容和数据类型也是错误的。 尝试将您的javascript代码更改为:

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