使用jquery将列表传递给控制器动作
本文关键字:控制器 jquery 列表 使用 | 更新日期: 2023-09-27 18:11:01
我目前将模型存储在JSON
对象中,这是一个包含不同数据(如id, name
等)的模型列表。我将这个模型传递回一个控制器动作。问题是List
包含正确的数量,但所有的数据与模型是空的。下面是我的代码:
模型:
#region Client Employees
public class EmployeesModel
{
public string Id { get; set; }
public string Division { get; set; }
public string Location { get; set; }
public string Level { get; set; }
public string Firm { get; set; }
public double? Bonus { get; set; }
public double? Salary { get; set; }
public double? Compensation { get; set; }
}
public class ViewEmployeesModel
{
public List<EmployeesModel> employees { get; set; }
}
#endregion
控制器:
public ActionResult Index()
{
var clients = DeepfieldClient.GetAllClientEmployees();
ViewEmployeesModel employees = new ViewEmployeesModel
{
employees = clients
};
return View(employees);
}
public JsonResult GetClients(List<EmployeesModel> model)
{
//Do something with the clients in the model
return Json(false);
}
Js:
GetClientData: function ()
{
$("#GetDataBtn").on("click", function () {
var searchCriteria = $(".dataSelectOptions").val();
$.ajax({
type: "POST",
url: "Home/GetClients",
data: { model: model },
success: function (response) {
GetData.FillTable(response);
}
});
});
},
模型在视图中存储为:
var model = @Html.Raw(Json.Encode(Model.employees))
任何想法,为什么我将检索正确的金额,但空值?
您需要在发送data
之前将其JSON.stringify()
。还可以用[HttpPost]
修饰控制器动作方法。contentType: "application/json"
:发送到服务器的数据类型,dataType: "json"
:期望返回的数据类型。
试试这个:
@section scripts{
<script type="text/javascript">
$(function () {
$("button").click(function(){
var model = @Html.Raw(Json.Encode(Model.employees));
$.ajax({
url: "@Url.Action("GetClients","Customers")",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(model)
})
.done(function(data){
console.log(data);
});
});
});
</script>
}
行动:
[HttpPost]
public JsonResult GetClients(List<EmployeesModel> model)
{
//Do something with the clients in the model
return Json(false);
}
JavaScript不知道model
是什么,试试:
data: { model: '@model' },