所以我一直在网上寻找一种方法将数据从我的js发送到我的控制器,并且遇到了一个看似很好的解决方案。
function syncDB() {
if (localStorage.length != 0) {
var data = viewLog();
for (var i = 0; i < localStorage.length; i++) {
$.ajax({
url: "/Leads/RegisterOfflineEntries",
type: "POST",
dataType: "json",
data: JSON.stringify(data)
});
}
}
}
发送到:
public ActionResult RegisterOfflineEntries(string[] leads)
{
string[] splitLeads;
for (int i = 0; i < leads.Length; i++)
{
splitLeads = leads[i].Split(',');
var validFields = new List<LeadFields>();
var fields = new List<LeadFields>
{
new LeadFields() {Value = splitLeads[0], FieldsId = 1},
new LeadFields() {Value = splitLeads[1], FieldsId = 2},
new LeadFields() {Value = splitLeads[2], FieldsId = 3},
new LeadFields() {Value = splitLeads[3], FieldsId = 4},
new LeadFields() {Value = splitLeads[4], FieldsId = 5}
};
foreach (var v in fields.Where(v => !(string.IsNullOrEmpty(v.Value))))
{
v.Value = v.Value.ToUpper();
validFields.Add(v);
}
}
return RedirectToAction("Index","Home");
}
现在,不要过多地读入代码,导致问题出在ActionMethod的参数中。它是空的,我无法弄清楚为什么,因为当我在其他地方使用js数据时,我可以读取它上面的数据,但是将它发送到控制器是不行的。
谢谢!
编辑: 我试图发送的对象是从viewLog方法获取的,看起来像这样
function viewLog() {
var localDbList = [localStorage.length];
for (var i = 0; i < localStorage.length; i++) {
localDbList[i] = localStorage[i];
}
return localDbList;
}
我拥有的是localStorage的离线支持,我尝试将这里存储的值保存在我的服务器上
编辑:
Request URL:http://localhost:59848/Leads/RegisterOfflineEntries
Request Headers
Provisional headers are shown
Accept:*/*
Content-Type:json
Origin:http://localhost:59848<br>
Referer:http://localhost:59848/Leads/Register
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:C8AD858A-EBA0-4A75-8D89-38956182F914
X-Requested-With:XMLHttpRequest
Request Payloadview source
[DAVE, DAVID, HAHA@MAIL.COM, , ]
0: "DAVE"
1: "DAVID"
2: "HAHA@MAIL.COM"
3: ""
4: ""
答案 0 :(得分:0)
您尚未发布data
所在的确切格式,在字符串化之前应该是这样的
var leadsStrings = new Array();
leadsStrings.push("string1");
leadsStrings.push("string2"); //etc
var dataObj = {
leads: leadsStrings
};
data : dataObj
function syncDB() {
var data = new Array();
if (localStorage.length != 0) {
for (var i = 0; i < localStorage.length; i++) {
data.push(localStorage[i]);
}
var dataObj = {
leads: data
};
$.ajax({
url: "/Leads/RegisterOfflineEntries",
data: dataObj
});
}
}
你的意思是这样吗?
答案 1 :(得分:0)
我不知道最初的问题是什么,从来没有真正解决过这个问题,而是我用API控制器做到了,所以它可以在后台顺利完成。如果感兴趣的话,请在下面编写代码
function OfflineSync() {
if (localStorage.length != 0) {
$.post('/api/TrackApi', { '': localStorage.length });
var formatedList = formatViewLog();
for (var k = 0; k < formatedList.length; k += 5) {
var value = JSON.stringify([
formatedList[k],
formatedList[k + 1],
formatedList[k + 2],
formatedList[k + 3],
formatedList[k + 4]
]);
$.post('/api/Offline', { '': value });
}
}
localStorage.clear();
}