这是我的 html
<ul class="sb_dropdown" style="display:none;">
<li class="sb_filter">Chon the loai</li>
<li><input type="checkbox" value="All"/><label for="all"><strong>Tất cả</strong></label></li>
<li><input type="checkbox" value="Woman"/><label for="Automotive">Đồ nữ</label></li>
<li><input type="checkbox" value="Shoes"/><label for="Baby">Giày</label></li>
<li><input type="checkbox" value="Bag"/><label for="Beauty">Túi sách</label></li>
<li><input type="checkbox" value="Man"/><label for="Books">Đồ nam</label></li>
</ul>
这是我的ajax调用控件,
<script>
$('.sb_search').click(function () {
var list = [];
$('ul.sb_dropdown').find("input:checkbox:checked").each(function () {
list.push($(this).val());
});
var key = { listkey: list };
$.ajax({
url: '@Url.Action("Search", "Result")',
traditional: true,
data: list,
dataType: "html",
type: 'POST',
success: function (data) {
alert("success");
},
error: function () {
alert("fail");
}
});
});
</script>
在我的 Controller 中,我有一个参数列表键,我希望当我单击按钮搜索时能从 View 中收到该参数列表键
public ActionResult Result()
{
return View();
}
[HttpPost]
public ActionResult Result(List<string> listkey)
{
var n = listkey;
return View();
}
当我调试这不是执行操作结果时,它会警告失败。告诉我我做错了什么。请帮助我了解 returnjson 为什么我需要使用而不是我想使用普通 View 来显示我的结果
我已经解决了这个问题,因为我在ajax中放置了错误的操作和 Controller 。谢谢大家
最佳答案
编辑尝试这个,创建数组并将其传递给您的 Controller
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { listkey: stringArray };
比你的ajax调用中的数据要多
data: postData
$.ajax({
type: "POST",
url: '@Url.Action("Search", "Result")',
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
<小时/>
你可以这样做,
- 将列表转换为 json 字符串,如下所示
您的数据将是data: '{ "listkey":' + JSON.stringify(list) + '}',
$.ajax({
url: '@Url.Action("Search", "Result")',
traditional: true,
data: '{ "listkey":' + JSON.stringify(list) + '}',
dataType: "html",
type: 'POST',
success: function (data) {
alert("success");
},
error: function () {
alert("fail");
}
});
而不是尝试看看你是否得到了你想要的结果
[HttpPost]
public ActionResult Result(List<string> listkey)
{
var n = listkey;
return View();
}
关于jquery - 如何通过ajax jquery将列表字符串从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26931042/