简体   繁体   English

通过json结果MVC渲染HTML部分视图

[英]Render Html partial view via json result MVC

ANSWER 回答

I went with a different approach on this one. 我对此采取了另一种方法。 Instead of loading the datatable from the server side, I decided to initialize the datatable once I would load the tbody via ajax and later on initialize the datatable. 我决定不通过服务器端加载数据表,而是决定先通过ajax加载tbody,然后再初始化数据表,从而初始化数据表。 That way, my page loads as normal, would then load the data via ajax and then the datatable is initialized so it can have all the features of datatable. 这样,我的页面将正常加载,然后将通过ajax加载数据,然后初始化数据表,使其具有数据表的所有功能。 In case it helps anyone, here is my script below. 万一它对任何人都有帮助,这是我的下面脚本。

$(document).ready(function () {
        $('#targetingtable tbody').block({
            message: "<i class='fa fa-spinner fa-spin'></i> Loading Data...",
            css: { border: '1px solid #aaa', padding: '10px 5px' },
            overlayCSS: { backgroundColor: 'rgba(196, 196, 196, .5)' }
        });
        $.ajax({
            url: '@Url.Action("GetDealerMediaRates", "Signup", new { cultureName = Model.CurrentCultureName })?ordersignupitemId=@Model.OrderSignupItemId&creativeTemplateId=@Model.CreativeTemplateId',
            type: "POST",
            dataType: "html",
            success: function (data) {
                var newHtml = $(data);
                $('.dealermediarates').html(newHtml);
                $('#targetingtable').DataTable({
                    'aoColumnDefs': [{
                        'bSortable': false,
                        'aTargets': ['nosort']
                    }],
                    'order': [[1, 'asc']],
                    'aLengthMenu': [[10, 25, 50, 100, 150, -1], [10, 25, 50, 100, 150, "All"]]
                });
                $('#targetingtable tbody').unblock();
            }
        });
        $('#targetingtable').unblock();
    });

UPDATE: 更新:

I am now able to get my partial view as a json result. 我现在可以将我的部分视图作为json结果。 The data displays on the site but the problem that I am running into now is I don't see any pagination that I get with the datatables. 数据显示在站点上,但是我现在遇到的问题是我看不到数据表的任何分页。 The Loading icon goes on and on. “加载”图标一直亮着。 Here is my updated code. 这是我更新的代码。 Am I doing anything wrong? 我做错什么了吗?

var rows = new SelectTargetingViewModel(signupService, orderSignupItem, creativeTemplateId, cultureName, false, dealermedias.OrderBy(d => d.Description).Skip(model.Start).Take(model.Length).ToList());
        string html = "";
        using (var sw = new StringWriter())
        {
            PartialViewResult partialresult = LoadGetDealerMediaPartialView(rows);
            partialresult.View = ViewEngines.Engines.FindPartialView(ControllerContext, "_GetDealerMediaRate").View;
            ViewContext vc = new ViewContext(ControllerContext, partialresult.View, partialresult.ViewData, partialresult.TempData, sw);
            partialresult.View.Render(vc, sw);
            html = sw.GetStringBuilder().ToString();
        }
        var result = new
        {
            recordsTotal = unfilteredCount,
            recordsFiltered = dealermedias.Count(),
            draw = model.Draw,
            data = rows.DealerMedias,
            resultset = html
        };
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    [HttpGet]
    public PartialViewResult LoadGetDealerMediaPartialView(SelectTargetingViewModel model)
    {
        return PartialView("_GetDealerMediaRate", model);
    }

//View //视图

$(document).ready(function () {
        $("#targetingtable").dataTable({
            "processing": true,
            "serverSide": true,
            "iDisplayLength": 10,
            "autoWidth": false,
            "ajax": {
                "url": '@Url.Action("GetDealerMediaRates", "Signup", new { cultureName = Model.CurrentCultureName })?ordersignupitemId=@Model.OrderSignupItemId&creativeTemplateId=@Model.CreativeTemplateId&columnheader=@Model.Description',
                "type": "POST",
                "dataType": "json",
                success: function (result) {
                    $('.dealermediarates').html(result.resultset);
                }
            },
            "aoColumnDefs": [{
                'bSortable': false,
                'aTargets': ['nosort']
            }],
            "order": [[1, 'asc']],
            "aLengthMenu": [[10, 25, 50, 100, 150, -1], [10, 25, 50, 100, 150, "All"]],
            "language": {
                "processing": "<i class='fa fa-spinner fa-spin'></i> Loading Data ..."
            }
        });
    });

在此处输入图片说明

// Below is what i submitted initially. // 以下是我最初提交的内容。

As my jquery datatable had some performance issue even though the total records the table could display in a given time doesn't exceed more than 300 rows, but still I am running into the performance issue. 由于我的jquery数据表存在一些性能问题,即使该表在给定时间内可以显示的总记录数不超过300行,但是仍然遇到性能问题。 Having said that, I am trying to load the data using the server side. 话虽如此,我正在尝试使用服务器端加载数据。 My columns are loaded dynamically based on the model data and based on the available columns in the model header, the rows are loaded appropriately. 根据模型数据动态加载我的列,并根据模型头中的可用列动态加载行。 Also, the datatable has some quantity fields that are all checkboxes. 同样,数据表具有一些均为复选框的数量字段。 All my table td elements are in a partial now, so I was wondering if there is a way to load the partial and pass it as a json result. 我所有的表td元素现在都位于部分中,所以我想知道是否有一种方法可以加载部分并将其作为json结果传递。 This is what I have so far. 到目前为止,这就是我所拥有的。

//Controller //控制器

var rows = new SelectTargetingViewModel(signupService, orderSignupItem, creativeTemplateId, cultureName, false, dealermedias.OrderBy(d => d.Description).Skip(model.Start).Take(model.Length).ToList());
        var result = new
        {
            recordsTotal = unfilteredCount,
            recordsFiltered = dealermedias.Count(),
            draw = model.Draw,
            data = rows.DealerMedias,
            resultset = LoadGetDealerMediaPartialView(rows)
        };
        return Json(result, JsonRequestBehavior.AllowGet);

[HttpGet]
    public ActionResult LoadGetDealerMediaPartialView(SelectTargetingViewModel model)
    {
        return PartialView("_GetDealerMediaRate", model);
    }

//View //视图

<tbody id="editorRows" class="dealermediarates"></tbody>

//client side //客户端

$(document).ready(function () {
        $("#targetingtable").dataTable({
            "processing": true,
            "serverSide": true,
            "iDisplayLength": 10,
            "autoWidth": false,
            "ajax": {
                "url": '@Url.Action("GetDealerMediaRates", "Signup", new { cultureName = Model.CurrentCultureName })?ordersignupitemId=@Model.OrderSignupItemId&creativeTemplateId=@Model.CreativeTemplateId&columnheader=@Model.Description',
                "type": "POST",
                dataType: 'json',
                success: function (data) {
                    $('.dealermediarates').html(data.resultset);
                }
            },
            "language": {
                "processing": "<i class='fa fa-spinner fa-spin'></i> Loading ..."
            },
            "aoColumnDefs": [{
                'bSortable': false,
                'aTargets': ['nosort']
            }],
            "order": [[1, 'asc']],
            "aLengthMenu": [[10, 25, 50, 100, 150, -1], [10, 25, 50, 100, 150, "All"]]
        });
    });

Is there anything wrong with this approach? 这种方法有什么问题吗? Currently, I don't get my rows when I do it this way and was wondering if this approach works, is there anything that I am missing? 目前,以这种方式执行操作时我没有得到任何行,并且想知道这种方法是否有效,是否缺少任何内容?

My experience with jQuery DataTables is limited so I can't accurately answer that part of the question. 我在jQuery DataTables方面的经验有限,因此我无法准确回答问题的这一部分。 DataTables-aside though, yes it is possible. 除了DataTables,是的,这是可能的。

You can pass back your model via a JsonResult action and then use jQuery to manipulate the DOM and update your HTML using values of the JSON object you received from the AJAX call, eliminating the need for a partial view altogether. 您可以通过JsonResult操作传递回模型,然后使用jQuery来操作DOM并使用从AJAX调用接收到的JSON对象的值更新HTML,从而完全不需要局部视图。

You can also have your ActionResult be a PartialViewResult ( ActionResult will still work since PartialViewResult is a type of ActionResult but this way you're being explicit about what your action can return) and replace the HTML with the HTML returned from the partial view. 你也可以有你ActionResultPartialViewResultActionResult仍会起作用,因为PartialViewResult是一个类型ActionResult但这种方式你是明确的关于你的行动可以返回),并取代HTML与HTML从局部视图返回。

Toy example of the latter below. 后者的玩具示例如下。


Main View 主视图

<div id="foobar">
    <!-- first time load -->
    @{ Html.RenderAction("FooBar", new { whateverParam = "whateverValue" }); }        
</div>

Partial View (Razor) 局部视图(剃刀)

@model FooBarViewModel

@foreach (Bar bar in Model.Foo)
{       
    <div>Content goes here</div>
}

Partial View (Action) 部分检视(动作)

public PartialViewResult FooBar(string whateverParam)
{
    return PartialView(fooBarViewModel);
}

jQuery jQuery的

$.ajax({
    url: "ControllerName/FooBar",
    data: {
            whateverParam: $("#whateverParam").val()
        },
        type: "GET",
        success: function (fooBarHTML) {
            $("#foobar").html(fooBarHTML);
        },
        error: function (xhr, status, errorThrown) {
            //...
        }
});

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

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