使用jquery将列表传递给控制器​​操作

时间:2015-09-03 20:30:12

标签: c# jquery model-view-controller

我目前在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))

为什么我会检索正确数量但是空值的任何想法?

2 个答案:

答案 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。