使用Ajax将本地存储传递给控制器 [英] Passing localstorage to controller using Ajax
问题描述
我需要访问存储在服务器端本地存储中的数据,但这是另一回事了.
I need to access the data held in localstorage, server side but that's another story.
我的视图中有此按钮:
<div style="float:right;">
<input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>
此JS函数:
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();
}
});
};
这个测试控制器方法:
[HttpPost]
[WebMethod]
public ActionResult Test(string JsonLocalStorageObj)
{
string x = JsonLocalStorageObj;
//deserialize here
return RedirectToAction("Index");
}
当我在chrome开发工具中运行 JSON.stringify(localStorage);
时,我会看到预期的数据,但是,当我调试控制器 JsonLocalStorageObj
时,始终是空
.作为测试,我使用了已注释掉的测试数组,并在控制器上设置了参数以接受 List< string>
,并且这些都是通过填充来实现的.
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.
JSON.stringify(localStorage);
传递有什么问题?
推荐答案
您尚未指定操作的参数名称(JsonLocalStorageObj),并且内容和dataType也是错误的.尝试将您的JavaScript代码更改为此:
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);
}
});
}
这篇关于使用Ajax将本地存储传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!