Render PartialView using Jquery Ajax in ASP.NET MVC

In this blog post, i want to share elegant method to render partial view as HTML string from ASP.NET MVC action method, which will be replaced or updated the browser DOM accordingly.

Here is the final UI, the table will updated with “Active” “InActive” click of radio button.

First create a new Visual Studio Project RenderPartialViewMVC using ASP.NET MVC Template.

Select the ProjectType


Select the Project Template

Creating the Model:
Create a simple data model, so you will have some data to work with.Go to Model folder and create a User class as below.

public class User
    {
        public long UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Status { get; set; }
        public List Users { get; set; } // this hold list of user to display as table.
    }

Code in the HomeController:

Modify the HomeController as below.

public class HomeController : Controller
    {
       //create a static property to hold the list of users between the requests.
        private static List<User> _users = new List<User>();
        [HttpGet]
        public ActionResult Index()
        {
          // populate the _users field with some data
            var user = new User();
            _users = new List<User>
            {
                new User{UserId=1, FirstName = "Sylvester", LastName="stolen", Status="Active"},
                new User{ UserId=1, FirstName = "John", LastName="Deo" , Status="InActive"},
                new User{ UserId=1, FirstName = "Eric", LastName="Waltor", Status="Active" },
                new User{UserId=1, FirstName = "Dom", LastName="Czubek", Status="Active"},
                new User{ UserId=1, FirstName = "John", LastName="King" , Status="InActive"},
                new User{ UserId=1, FirstName = "Anne", LastName="Burtorm", Status="Active" }
            };
            //user.Status = "Active";
            user.Users = _users;
            return View(user);
        }
        [HttpPost]
        public ActionResult Index(User user)
        {
            //var selectedRadioValue = userInformation.Gender;
            var userModel = new User();
            var _selectedList = new List<User>();
            if (user != null)
            {
                var strStatus = user.Status.ToUpper();
                _selectedList = (from u in _users
                                 where u.Status.Trim().ToUpper() == user.Status.ToUpper()
                                 select u).ToList();
            }
            userModel.Users = _selectedList;
            return View(userModel);
        }
        // This action method return HTML partial view as JSON sring 
        [HttpGet]
        public JsonResult GetUsersByStatus(string status)
        {
            var user = new User();
            var _usersByStatus = (from u in _users
                                  where u.Status.Trim().ToUpper() == status.ToUpper()
                                  select u).ToList();
            user.Users = _usersByStatus;
            var UsersPartialView = RenderRazorViewToString(this.ControllerContext, "_UsersPartialView", user);
            var json = Json(new { UsersPartialView }, JsonRequestBehavior.AllowGet);
            return json;

            //return Json(_usersByStatus, JsonRequestBehavior.AllowGet);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        // Convert Razor view to string using C#
       <strong> public static String RenderRazorViewToString(ControllerContext controllerContext, String viewName, Object model)
        {
            controllerContext.Controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, 
                                   controllerContext.Controller.TempData, sw);
                ViewResult.View.Render(ViewContext, sw);
                ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }</strong>
    }

Now we need to create a partial view which shows the HTML we get from server when we make a ajax call to update the UI.
go to Views -> Home, create a partial view as “_UsersPartialView.cshtml“, here is the content.

@model RadioButtonModelBinding.Models.User

@if (Model.Users != null)
{
    if (Model.Users.Count > 0)
    {
        <table id="usersTable" class="table  table-condensed table-striped table-hover table-bordered">
            <thead class="label-default">
                <tr>
                    <th>First Name </th>
                    <th>
                        Last Name
                    </th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Users)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                        <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                        <td>@Html.DisplayFor(modelItem => item.Status)</td>
                        <td class="hide">@Html.DisplayFor(modelItem => item.UserId) </td>
                    </tr>
                }
            </tbody>
        </table>
    }
}

Now modify the Index.cshtml view under Views-> Home directory as below

@model RadioButtonModelBinding.Models.User
@{
    ViewBag.Title = "Home Page";
}

<form class="form-horizontal" action="@Url.Action("Index", "home")" method="post">
    <div class="form-group">
        <div class="col-md-10">
            @Html.LabelFor(model => model.Status, "Active")
            @Html.RadioButtonFor(model => model.Status, "Active", new { @class = "rdgroup", id = "rdGroupOne" })
            @Html.LabelFor(model => model.Status, "InActive")
            @Html.RadioButtonFor(model => model.Status, "InActive", new { @class = "rdgroup", id = "rdGroupOne" })
        </div>
    </div>
    <div class="form-group">
        <div class="table-responsive">
            <div id="dvUsersPartialView">
                @Html.Partial("_UsersPartialView", Model)
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="CreateUser" class="btn btn-default" />
        </div>
    </div>

</form>

finally add below JavaScript in the Index.cshtml file to call the ASP.NET MVC action method and update the browser DOM UI with partial view html string from the server.

@section Scripts {

    <script language="javascript">
        $(document).ready(function () {
            $('input[name=Status]').click(function () {
                var selectedStatus = $('input[name=Status]:checked').val();
                // Ajax call to get the users by the selected status.
                $.ajax({
                    url: '@Url.Action("GetUsersByStatus")',
                    cache: false,
                    type: "GET",
                    dataType: "JSON",
                    data: { status: selectedStatus },
                    success: function (UsersPartialView) {
                        $("#dvUsersPartialView").html(UsersPartialView.UsersPartialView);
                    }
                });

            });
        });



    </script>
}

Here is the final out put of the UI.
On page load, UI show both Active and Inactive records.

click on any active or inactive radio button, users table will be updated with the results from the server.

that’s it , let me know if you have any questions or feedback.

local_offerevent_note September 18, 2019

account_box srinivasaraju nadimpalli