我的controller Action method
如下所示:
[HttpGet]
[Route("ShowModal")]
public Task<IActionResult> GetDetails(int id, string name, IEnumerable<Employee> employees)
{
//create a model
//Some business logic codes
return PartialView("_Partial.cshtml", model);
}
我需要从jQuery's $.get()
调用上面的Action方法单击按钮时的方法,捕获返回的部分 View HTML
,并在 Bootstrap 弹出窗口中显示它。
我无法通过 IEnumerable<Employee>
来自jQuery
方法,它总是 null
,无论我尝试什么。
下面是JS代码:
<a class="btn btn-primary" onclick="ShowModal();" data-keyboard="true" data-toggle="modal">ShowModal</a>
<div class="modal fade" id="divShowModalDialog" role="dialog" tabindex="-1">
<div class="modal-body" id="divShowModalBody">
</div>
</div>
function ShowModal()
{
var list = [{ Id: 101, Gender: 'MALE' }, { Id: 102, Gender: 'FEMALE' }];
list = JSON.stringify(list);
var data = { 'id': 999, 'name': 'JAMES', 'employees': list };
$.get('/Area1/Controller1/ShowModal', data)
.done(function (response) {
if (response != undefined) {
$('#divShowModalBody').html(response);
$('#divShowModalDialog').modal(
{
backdrop: 'static',
keyboard: true,
});
}
})
.fail(function (xhr) {
console.log(xhr);
})
}
我得到id
和name
Action 方法中的参数,但列表始终为空。我在删除 JSON.stringify()
后尝试过也是如此,但它不起作用。
我知道我错过了一件微不足道的事情,请帮忙。
最佳答案
首先,您应该使用 [HttpPost]
在您的 Controller 操作上,而不是 [HttpGet]
,当然你需要使用来自 jQuery 的 post ,它使用 $.post()那是因为“POST”是正确的 - 但不是唯一的 - HTTP动词,实际将数据发送到服务器端。
其次,在将员工列表放入 data
之前,不应对其进行字符串化。您发送的 javascript 对象。
所以,<罢工> list = JSON.stringify(list);
然后立即出发
var data = { 'id': 999, 'name': 'JAMES', 'employees': list };
您可能还需要使用 $.post(url,data,onsucess,dataType)
提供数据类型检查上面链接中的文档。
最后,在您的操作方法中删除 IEnumerable<T>
并将其替换为具体的集合类型,如 List<T>
因为 JSON 序列化程序需要知道在绑定(bind)时要实例化哪种类型的集合。
关于javascript - 将项目列表从 $.get() 传递到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39158029/