RenderPartialViewToString / Return multiple partial views in JSON - MVC6

by Admin 5. May 2016 00:00

I got a situation where we need to dynamically render multiple partial views and bid on the view in MVC6

So Here is the solution.

This is the common method for rendering the partial views as strings

protected string RenderPartialViewToString(string viewName, object model)

        {

            if (string.IsNullOrEmpty(viewName))

                viewName = ActionContext.ActionDescriptor.Name;

 

            ViewData.Model = model;

 

            using (var sw = new StringWriter())

            {

                var engine = Resolver.GetService(typeof(ICompositeViewEngine))

                    as ICompositeViewEngine;

                var viewResult = engine.FindPartialView(ActionContext, viewName);

 

                var viewContext = new ViewContext(

                    ActionContext,

                    viewResult.View,

                    ViewData,

                    TempData,

                    sw,

                    new HtmlHelperOptions()

                );

                //Everything is async now!

                var t = viewResult.View.RenderAsync(viewContext);

                t.Wait();

                return sw.GetStringBuilder().ToString();

            }

        }

 

Here is the method for the view which returns multiple partial view results as JSON

public async Task<ActionResult> GetMultiplePartialsAsync(Your input parameters go here)

        {

            var viewModel = await _myService.FetchDatasAsync(Your input parameters go here);

   //For brevity I am assigning the same view model to all the partial views.

   //You can have sub models in the view model too

                var json = Json(new

                {

                    FilterPartialViewHtml = RenderPartialViewToString("PagedResults", viewModel),

                    CountriesPartialViewHtml = RenderPartialViewToString("Countries", viewModel),

                    NamesPartialViewHtml = RenderPartialViewToString("Names", viewModel)

                });

                return json;

 

        }

 

Here is my View which load all the 3 partial views on load & on click of a checkbox

Note that the paritals are loaded on load as well as gets reladed on all onchange events of the checkbox for countries & Names

@model ResultViewModel

@{

    Layout = "~/Views/Shared/_DemoLayout.cshtml";

}

<div id="wrapper">

    <main id="content" role="main">

            

            <div class="filtering">

                <div class="filter-form">

                    <div class="inner-block">

                        <form method="get" action="Filter">

                            <div class="filter text-filter">

                                <label class="legend" for="finder-keyword-search">Search</label>

                                <input value="" type="text" name="Keywords" id="Keywords" aria-controls="js-search-results-info" class="text">

                            </div>

                            <div id="divCenturies">

                            </div>

                            <div id="divLastNames">

                            </div>

                        </form>

                    </div>

                </div>

                <div class="js-live-search-results-block">

                    <div class="filtered-results">

                            <div id="searchResults">

                            </div>

                            

                    </div>

                </div>

            </div>

    </main>

</div>

<script>

    var url = '@Url.Action("GetMultiplePartialsAsync", "Search")';

 

    $(window).load(function () {

        SearchData();

        $('#searchResults').hide();

    });

 

    $(document).ready(function () {

        $('#searchResults').hide();

        $('#divCenturies').hide();

        $('#divLastNames').hide();

        $(document).on("change", "input[type=checkbox]", function () {

            SearchData();

        });

 

        $("#Keywords").change(function () {

            SearchData();

        });

        $("#Keywords").keypress(function (e) {

            if ((e.keyCode || e.which) == 13) {

                e.preventDefault();

                SearchData();

            }

        });

    });

 

    function SearchData() {

        $.get(url, { Your input parameters here },

                function (data) {

                    $("#searchResults").html(data.FilterPartialViewHtml);

                    $("#divCenturies").html(data.CountriesPartialViewHtml);

                    $("#divLastNames").html(data.NamesPartialViewHtml);

                });

        $('#searchResults').show();

        $('#divCenturies').show();

        $('#divLastNames').show();

    }

</script>

 

Tags:

Comments are closed

TextBox

Tag cloud

    RecentPosts