将jQuery ajax响应绑定到MVC模型表中

4
我正在尝试将一个ajax响应数组推入MVC表中。 这是我的脚本的样子:
<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>

这是我的部分视图的样子:
@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>

这是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;
}

这是视图的样子:

@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>

问题:我正在尝试通过WebApi获取详细信息列表并将其绑定到MVC表格。怎样做最好?

我使用了下面的代码来填充Grid,但是表格没有任何数据。请问有没有人能够给我一个使用上述部分视图来填充Grid的想法。非常感谢!

$("#Grid").html($(data).children());


你需要重新构建表格,因为从你的服务器传递过来的数据是C#中的IEnumerable对象。 - Rajshekar Reddy
2个回答

2
你的 Web API 端点返回的是数据(以 JSON 格式),而不是你的部分视图中的 HTML 标记。你有两个选项。
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);
}

现在,请确保在~/Views/Shared或者~/View/YourControllerName/中有一个名为GetDepotDetails.cshtml的局部视图。该视图应该是强类型化到一个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>

在您的成功事件中,

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

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);
         },

你能给我一个例子吗? - Dayan
我正在尝试将此部分添加到MVC操作方法 - 'return PartialView(model);'......它给我一个错误,说'无法隐式转换部分视图为IEnumerable'。你知道该怎么办吗? - Dayan
抱歉!我不太明白你在说什么。Grid 是 ID,有什么问题吗?它是如何导致多个 ajax 调用的? - Shyju

2

既然您已经有了构建表格的部分视图,那么您可以这样做。

在您的ajax成功方法中调用一个控制器操作,通过传递从API接收到的数据。控制器将通过传递相同的模型来返回现有的部分视图。

        $.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);
                }
            });

正如我所说的那样,创建一个新的MVC操作方法,并通过从ajax发送的模型传递相同的部分视图。

或者你可以使用Jquery重新构建表格 - 但如果表格HTML很大(带有css,属性,动态属性等),这是一种痛苦。 - 我认为其他答案已经详细说明了这一点。


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