简体   繁体   English

jQuery ajax响应绑定到MVC Model表

[英]jQuery ajax response bind into MVC Model table

I'm trying to push an ajax response array into MVC table. 我正在尝试将ajax响应数组推入MVC表。 This is how my script looks like: 这是我的脚本的样子:

<script type="text/javascript">

    $(document).ready(function () {
        $('#form1').submit(function (event) {
            event.preventDefault();
            event.returnValue = false;
            var selectValue = $('#selectValue').val();

            $.ajax({
                url: "/api/Admin/GetDepotDetails/",
                type: "POST",
                data: { "selectValue": selectValue },
                dataType: "json",
                success: function (data) {
                    $("#Grid").html($(data).children());
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    debugger;
                    alert(textStatus, errorThrown, jqXHR);
                }
            });
        });
    });



</script>

This is how my partial view looks like: 这是我的局部视图的样子:

@model IEnumerable<SampleApp.DepotDetail>

<table class="table table-condensed" id="Grid">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.DepotID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ColumnName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Country)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CountryCode)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr class="warning">
            <td>
                @Html.DisplayFor(modelItem => item.DepotID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ColumnName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CountryCode)
            </td>
        </tr>
    }

</table>

This is how the WebApi method looks like: 这就是WebApi方法的样子:

[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
    var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue) as IEnumerable<DepotDetail>;
    var viewModel = new SearchViewModel{ DepotDetailsList = model, ActionLists = new ActionList()} ;
    return model;
}

This is how the View looks like: 这就是View的样子:

@model IEnumerable<SiemensSampleApp.DepotDetail>
<div class="row">
    <div class="col-md-4">
        <form id="form1">
            @*@Html.DropDownListFor(model => model.DepotListSelectValue, Model.DepotLists, new { @class = "form-control" })*@

            @Html.DropDownList("selectValue", new List<SelectListItem>
            {
                new SelectListItem() {Text = "Depot ID", Value="Depot ID"},
                new SelectListItem() {Text = "Depot Name", Value="Depot Name"},
                new SelectListItem() {Text = "Address", Value="Address"}
            }, new { @class = "selectValue", @id = "selectValue" })
            @*//, new { @class = "chzn-select", @id = "chzn-select" }*@





            <input type="submit" value="submit" />
        </form>
        <br /><br /><br />
        <table id="records_table" style="width:100%;"></table>

        <div id="tableHere">
            @{
                if (Model == null)
                {
                    Html.RenderPartial("_SearchResult", new List<DepotDetail>() { });
                }
            }


        </div>

    </div>

</div>

Question: Through WebApi i'm trying to get a List of details and bind it to a MVC table. 问题:通过WebApi,我试图获取详细信息列表并将其绑定到MVC表。 What is the best way to do this? 做这个的最好方式是什么? I have used 我用过

$("#Grid").html($(data).children()); $( “#网格”)HTML($(数据)。儿童());

To fill the Grid. 填补网格。 But the table doesn't have any data. 但该表没有任何数据。 can someone please give me an idea how to fill the grid using above Partial view. 有人可以让我知道如何使用上面的部分视图填充网格。 Thank you in advance! 先感谢您!

Your web api endpoint return data ( in json format), not the HTML markup from your partial view. 您的web api端点返回数据(采用json格式),而不是部分视图中的HTML标记。 You have 2 options. 你有2个选择。

1) Create an mvc action method which gets the data and pass it to your partial view and return the partial view response and use that to update your UI 1)创建一个mvc动作方法,该方法获取数据并将其传递给局部视图并返回部分视图响应并使用它来更新UI

[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
    var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue) 
                                                             as IEnumerable<DepotDetail>;

    return PartialView(model);
}

Now make sure you have a partial view called GetDepotDetails.cshtml in ~/Views/Shared or ~/View/YourControllerName/ . 现在确保在~/Views/Shared~/View/YourControllerName/有一个名为GetDepotDetails.cshtml的局部视图。 This view should be strongly typed to a collecction of DepotDetail. 这个视图应该强烈地输入到DepotDetail的集合中。

@model IEnumerable<DepotDetail>

<p>Here loop through each item in Model and render the table</p>
<p> Same as your partial view in the question </p>

And in your success event, 在你的成功活动中,

success: function (data) {
               $("#Grid").html(data);
         },

2) Use your current web api endpoint and read the data in your ajax method's success event and dynamically build the html markup for the table rows and set that as the content of your Grid table. 2)使用当前的web api端点并读取ajax方法success事件中的数据,并动态构建表行的html标记,并将其设置为Grid表的内容。

success: function (data) {
             var tblHtml="";
             $.each(data.DepotDetailsList,function(a,b){

                       tblHtml+= "<tr><td>"+b.DepotID+"</td>";
                       tblHtml+= "<td>"+b.ColumnName+"</td>";
                       tblHtml+= "<td>"+b.Country+"</td>";
                       tblHtml+= "<td>"+b.CountryCode+"</td>M/tr>";

             });
             $("#Grid > tbody").html(tblHtml);
         },

Since you already have the partial view which build the table, you can do this. 由于您已经拥有构建表的局部视图,因此您可以执行此操作。

In your ajax success method call a controller action by passing this data received from the API. 在您的ajax success方法中,通过传递从API接收的数据来调用控制器操作。 The controller will just return the existing partial view by passing the same model. 控制器将通过传递相同的模型返回现有的局部视图。

        $.ajax({
                url: "/api/Admin/GetDepotDetails/",
                type: "POST",
                data: { "selectValue": selectValue },
                dataType: "json",
                success: function (data) {
                    //$("#Grid").html($(data).children());
                     $.get("controller/Action",data.DepotDetailsList ,function(response){
                       $('#tableHolder').html(response) //have a div in your main view which will hold the table. Now the partial view has to be replaced into this div.
                     });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    debugger;
                    alert(textStatus, errorThrown, jqXHR);
                }
            });

So as I said, Create a new MVC action method and return a the same partial view by passing the model sent from ajax. 正如我所说,创建一个新的MVC操作方法并通过传递从ajax发送的模型返回相同的局部视图。

OR you can user Jquery and build the table again - But this is a pain if the table HTML is large (with css, attributes, dynamic arributes etc). 或者您可以使用Jquery并再次构建表 - 但如果表HTML很大(使用css,属性,动态到达等),这将是一个痛苦。 - I think the other answer already has the details on this - 我认为另一个答案已经有了详细说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM