如何在ajax post请求中传递模型?

5
大家好,我是一名新手ASP MVC程序员。我需要将我的模型作为参数传递给Ajax POST请求。
以下是我的Ajax POST请求代码:
<script type="text/javascript">
        $(document).ready(function () {
            $("#contragentTable tr").click(function () {                   
                $.ajax({
                    type: 'POST',
                    url: "/Contragent/Index",
                    data: $('#form').serialize(),                              
                    dataType: 'json'                    
                });
            });
        });

</script>

这是模型。
public class ContragentModel
{
    private readonly List<ContragentView> contragentList = new List<ContragentView>();

    public ContragentModel()
    {
        this.IsRowSelected = false;
    }

    public List<ContragentView> ContragentList
    {
        get
        {
            return this.contragentList;
        }
    }  

    public ContragentView SelectedContragent { get; set; }

    public bool IsRowSelected { get; set; }
}

这些是控制器。
public ActionResult Index()
{           
    var contragentModel = new ContragentModel();
    var contragentView = new ContragentView();
    contragentView.Id = 1;            
    contragentModel.ContragentList.Add(contragentView);           

    return View(contragentModel);
}    

[HttpPost]
public ActionResult Index(ContragentModel model)
{           
    model.IsRowSelected = true;

    // Here exception throws, because there no items 
    model.SelectedContragent = model.ContragentList.Single(t=>t.Id== 1);

    return this.RedirectToAction("Index", model);            
}

当我通过ajax post请求传递我的模型时,model.ContragentList没有项目。然而在cshtml端它有。有人知道为什么吗?
另外,我该如何在我的ajax请求中传递模型和多个int参数?
这是我的视图:
@model Transportation.Models.ContragentModel
@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_MainLayout.cshtml";
}

@section head{
    <script type="text/javascript">    
        $(document).ready(function () {
            $("#contragentTable tr").click(function () {                   
                $.ajax({
                    type: 'POST',
                    url: "/Contragent/Index",
                    data: $('#form').serialize(),                          
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8'
                });
            });
        });

    </script>    
}

<table id="contragentTable" class="table table-hover table-bordered">
    <tr id="0" style="background-color: #ccc">        
        <th>
          @Html.ActionLink("some text1", "Index")
        </th>
        <th>
            @Html.ActionLink("some text2", "Index")
        </th>
        <th />
        <th></th>
    </tr>

    @if (@Model.ContragentList.Count > 0)
    {            
        <tr id="@index.ToString()">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>          
    }
    else
    {
        <tr>
            <td colspan="9">No data
            </td>
        </tr>
    }
</table>

<div>    
    @{ var displayStyle = @Model.IsRowSelected ? "" : "none";    
       var operationTypeGroups = Model.IsRowSelected ? Model.SelectedContragent.PriceList.GroupBy(t => t.OperationTypeId) : null;    
       var operationTypes = operationTypeGroups == null ? null : operationTypeGroups.SelectMany(t => t);

        <table id="priceTable" class="table table-hover table-bordered" style="display: @displayStyle">
            <tr id="0" style="background-color: #ccc">
                <th>

                </th>
                <th>

                </th>

                @if (operationTypes != null)
                {
                    foreach (var operationType in operationTypes)
                    {
                    <th>
                        @Html.ActionLink(operationType.OperationTypeName, "Index");
                    </th>
                    }
                }

                <th></th>
            </tr>

        </table>
    }

</div>

你能在视图中展示一下你的表单包含哪些输入字段吗? - Darin Dimitrov
在我的视图中,我有一个用于显示“model.ContragentList”中项目的表格。当我点击表格行时,会执行AJAX请求。但是在我的控制器端,我在“model.ContragentList”集合中没有任何项目。 - user3024496
输入项必须具有名称属性,答案中提到的内容类型必须设置... @DarinDimitrov我认为数据属性应该像{model:serializedform}这样。 - Vishal Sharma
不需要设置任何内容类型,如果您直接序列化表单,它将默认使用application/x-www-form-urlencoded。而且,您不应该使用{ model: serializedform }。唯一的要求是具有正确的输入字段名称。这就是为什么我要求OP展示他的视图以查看他如何生成相应的输入字段。不幸的是,他似乎没有回应,所以我们只能在这里猜测并提出建议,而不能提供有建设性的答案。 - Darin Dimitrov
我将我的视图代码添加到我的问题中。 - user3024496
@user3024496,您想要发送模型链接吗?当您序列化表单时,它当然不包括链接... - Vishal Sharma
1个回答

6
请查看这篇文章:http://www.codeproject.com/Articles/678591/CRUD-Operations-using-Partial-V 本文介绍了如何在ASP.NET MVC 4应用程序中使用jQuery AJAX调用进行CRUD操作。
对于您的代码,您需要修改以下行:
            $("#contragentTable tr").click(function () {
                var modelDataJSON = '@Html.Raw(Json.Encode(Model))';

                $.ajax({
                url: "/Contragent/Index",
                type: 'POST',                   
                data: { myObject1: modelDataJSON},                              
                dataType: 'json'                    
                });
             });                   

在进行AJAX调用时,您必须为对象提供名称,并且它应与目标控制器操作方法中的参数名称相同。由于您从客户端发送JSON,因此操作方法应如下:

public ActionResult Index(string myObject1 ) 

那么在 action 内部,您可以反序列化 JSON 对象并创建模型或进行其他所需的处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接