我目前在id, name
对象中存储模型,该模型是包含JSON
等不同数据的模型列表。我将此模型传递回控制器操作。问题是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))
为什么我会检索正确数量但是空值的任何想法?
答案 0 :(得分:1)
在发送之前,您需要JSON.stringify()
data
。并使用[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);
}
答案 1 :(得分:0)
JavaScript不知道model
是什么,请尝试:
data: { model: '@model' },
数据是Razor而不是JavaScript。