[英]Pass Data by AJAX to Controller in MVC
我正在尝试将数据传递给控制器以进行进一步处理,但控制器中为空,但是无论如何,js(ajax)的调试都会显示该数字。 可能是什么问题?
阿贾克斯:
$('.toggler_btn').on('click', function (event)
{
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: "/List/GetSubItems",
type: "POST",
contentType: "html",
dataType: "text",
data: '{"id":"' + id + '"}', // here it show the data, like 5 or some other number
success: function (data)
{
$('.element_wrapper [data-id="' + id + '"]').html(data);
}
})
$(this).html('-');
}
else $(this).html('+');
});
控制器:
[HttpPost]
public ActionResult GetSubItems(string id) // here I get null
{
int pID = 0;
int.TryParse(id, out pID);
List<H_Table> list = new List<H_Table>();
foreach (var item in db_connection.H_Table.Where(i => i.PARENT_ID == pID))
{
list.Add(item);
}
return PartialView(list);
}
$('.toggler_btn').on('click', function (event) {
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: '/List/GetSubItems',
type: 'POST',
dataType: 'json',
data: '{"id":"' + id + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.element_wrapper [data-id="' + id + '"]').html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
}
});
$(this).html('-');
}
else $(this).html('+');
});
使用这个只需复制和粘贴
将您的内容类型更改为“文本”,并更改数据。
您的AJAX请求已设置了contentType: "html"
但实际上您正在发送JSON( data: '{"id":"' + id + '"}'
)。 并且您的控制器正在接收string
。
因此,要么更改您的AJAX调用以发送原始字符串:
contentType: "text",
data: { id: id }
...或更新您的控制器以接收JSON。 后者可以通过创建如下代码来实现:
public ActionResult GetSubItems(ViewModel model)
public class ViewModel {
public string Id { get; set; }
}
编辑 :另外,作为参考,您可能希望查看contentType
和dataType
之间的区别 。
将数据类型更改为“ application / json”,并将数据更改为此:
data :{
id : id
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.