【问题标题】:How to pass model in ajax post request?如何在ajax post请求中传递模型?
【发布时间】:2015-05-26 04:21:01
【问题描述】:

大家。 我是asp mvc的新手。我需要在 ajax 发布请求中将我的模型作为参数传递。

这是我的 ajax 发布请求代码:

<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 发布请求中传递我的模型时,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>

【问题讨论】:

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

标签: c# jquery ajax asp.net-mvc


【解决方案1】:

请看文章:http://www.codeproject.com/Articles/678591/CRUD-Operations-using-Partial-V

在本文中,CRUD 操作是在 ASP.NET MVC 4 应用程序中使用 jQuery AJAX 调用执行的。

关于您的代码,您需要修改以下行:

            $("#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 对象并创建模型或您需要的任何处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2016-07-11
    • 2021-11-01
    • 2022-10-05
    • 1970-01-01
    相关资源
    最近更新 更多