通过json结果MVC渲染HTML部分视图 [英] Render Html partial view via json result MVC

查看:127
本文介绍了通过json结果MVC渲染HTML部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案

在这个问题上,我采取了另一种方法.不再从服务器端加载数据表,而是决定先通过ajax加载tbody,然后再初始化数据表,然后初始化数据表.这样,我的页面将正常加载,然后将通过ajax加载数据,然后初始化数据表,使其具有数据表的所有功能.万一它对任何人都有帮助,这是下面的脚本.

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

更新:

我现在可以将我的部分视图作为json结果.数据显示在站点上,但是我现在遇到的问题是我看不到数据表的任何分页.加载"图标一直亮着.这是我更新的代码.我做错什么了吗?

I am now able to get my partial view as a json result. 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);
    }

//查看

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

//以下是我最初提交的内容.

由于我的jquery数据表存在一些性能问题,即使该表在给定时间内可以显示的总记录不超过300行,但是我仍然遇到性能问题.话虽如此,我正在尝试使用服务器端加载数据.根据模型数据动态加载我的列,并根据模型标题中的可用列动态加载行.另外,数据表具有一些均为复选框的数量字段.我所有的表td元素现在都位于部分中,所以我想知道是否有一种方法可以加载部分并将其作为json结果传递.这就是我到目前为止所拥有的.

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. 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. This is what I have so far.

//控制器

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

//查看

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

//客户端

$(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?

推荐答案

我对jQuery DataTables的经验有限,因此我无法准确回答问题的这一部分.除了DataTables,是的,这是可能的.

My experience with jQuery DataTables is limited so I can't accurately answer that part of the question. DataTables-aside though, yes it is possible.

您可以通过 JsonResult 操作传回模型,然后使用jQuery来操作DOM并使用从AJAX调用接收到的JSON对象的值更新HTML,从而无需使用完全部分视图.

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.

您还可以将您的 ActionResult 设置为 PartialViewResult (由于 PartialViewResult 是一种类型, ActionResult 仍然可以使用的 ActionResult ,但是通过这种方式,您可以明确知道操作可以返回的内容),并将HTML替换为部分视图返回的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.

下面是后者的玩具示例.

Toy example of the latter below.

主视图

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

局部视图(剃刀)

@model FooBarViewModel

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

部分视图(操作)

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

jQuery

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

这篇关于通过json结果MVC渲染HTML部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆