0

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. 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 })[email protected]&[email protected]',
            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. 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 })[email protected]&[email protected]&[email protected]',
                "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 ..."
            }
        });
    });

enter image description here

//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. 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.

//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 })[email protected]&[email protected]&[email protected]',
                "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?

1 Answer 1

1

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.

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.

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.


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

$.ajax({
    url: "ControllerName/FooBar",
    data: {
            whateverParam: $("#whateverParam").val()
        },
        type: "GET",
        success: function (fooBarHTML) {
            $("#foobar").html(fooBarHTML);
        },
        error: function (xhr, status, errorThrown) {
            //...
        }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help trashr0x. My question was on how to get the partialview as a json result. I have in several places displayed partial view from an ajax call, no issue there. Just wanted to know if it was possible to get the partial view through a json result that I could then use on the view to render to html. I think I was able to do that, take a look at my updated section above. Now, my datatable is not rendering the pagination and the loading icon keeps showing up. The rows are now showing up on the datatable.
@bladerunner Still not clear from this thread that have you been able to solve the issue of loading a column text as a partial view when using DataTable server side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.