Click here to Skip to main content
15,868,048 members
Articles / Web Development / ASP.NET

How to Render MVC View on a Modal Popup Window

Rate me:
Please Sign up or sign in to vote.
4.77/5 (15 votes)
16 Jan 2012CPOL3 min read 179.9K   19   8
How to render MVC view on a Modal popup window

Image 1

You might be wondering how to place an MVC View easily on a pop-up window like the image above, that’s why you are on this page now?

Well, you are a bit lucky as I will tell you how easy this is to execute, but first of all, let me tell you that I am using the Window Control from Telerik Extensions for ASP.NET MVC to make my life easy and not re-invent the wheel and if you don’t have problems with that, then read ahead.

Now let's start. Let's pretend we want an application to set up a new client Account and what we want is when a user clicks a link create account, it will pop up a window for account creation. So like any other MVC Application, you need your Model which in this case we will call “AccountSetupViewModel” which is a model for setting up accounts, a View for the pop up which we can call “NewAccount.cshtml” and Controller which we can call “SetupController”. We also need some JavaScript file to separate our JavaScript commands to others for a cleaner implementation.

Let's first make our ViewModel in AccountSetupViewModel.cs under Controllers -> ViewModels -> Setup folder, we will make it simple so it will only contain AccountCode and AccountName.

C#
public class AccountSetupViewModel
{
    [Required]
    public string AccountCode { get; set; }

    [Required]
    public string AccountName { get; set; }
}

Now let's create a query to execute with firstName and lastName as a parameter and name it as GetAccountViewModel which we will place in AccountSetupQuery.cs under Controllers -> Queries -> Setup, you can also create an interface for it if you wish. This method will combine the firstName and lastName and sets the AccountName ViewModel.

C#
public AccountSetupViewModel GetAccountViewModel(string firstName, string lastName)
{
    var viewModel = new AccountSetupViewModel();

    viewModel.AccountCode = "RSM";
    viewModel.AccountName = firstName + " " + lastName;

    return viewModel;
}

Now let's create our Controller called SetupController.cs just in the Controllers directory and create a method called “GetNewAccountViewHtml”, this will be the method that will output a JsonResult to render our view:

C#
[HttpPost]
public JsonResult GetNewAccountViewHtml(string firstName, string lastName)
{
    string viewHtml = string.Empty;
    var viewModel = accountSetupQuery.GetAccountViewModel(firstName, lastName);

    viewHtml = RenderRazorViewToString("NewAccount", viewModel);

    var hashtable = new Hashtable();
    hashtable["viewHtml"] = viewHtml;

    return Json(hashtable);
}

You notice we have a method called RenderRazorViewToString, like how it’s called, its purpose is to Render the MVC Razor View to string. We will be using the MVC engine to render the view model as HTML so we can easily place it on the pop-up window. You can place it in the controller but best if there is a separate class for this as you will definitely reuse this a lot.

C#
private string RenderRazorViewToString(string viewName, object model)
{
    ViewData.Model = model;

    using (var stringWriter = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext
                          (ControllerContext, viewResult.View, ViewData, TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

        return stringWriter.GetStringBuilder().ToString();
    }
}

Next let's create a view and call it “NewAccount.cshtml” and place it in Views -> Setup, this is the view that we will be using on the pop-up window.

C#
@model CI5.Web.Mvc.Controllers.ViewModels.Setup.AccountSetupViewModel
@using Telerik.Web.Mvc.UI;
@{
    Layout = null;
}

This is an MVC view in a pop up <br />
Account Code : @Model.AccountCode <br />
Account Name : @Model.AccountName

Now you have all of the contents you need for that pop-up, now let's create a view to call the pop-up we can use “Default.cshtml” under View -> Setup Folder in this instance. On your view, it will be as simple as registering JavaScript on an a link to pop up the window so put this on your view.

XML
<li class="newclient"><a href="#newClient" title="" 
  onclick="javascript:AccountSetupForm.displayPopUpWindow('Raymund', 'Macaalay');">
  New Client</a></li>

Then using a JavaScript file that initializes on load of the “_SiteLayout.cshtml

C#
<script src="@Url.Content("~/Scripts/AccountSetup.js")" type="text/javascript"></script>

which we call “AccountSetup.js” located in Scripts folder we will create a function trigger the Telerik window pop up.

C#
var AccountSetupForm = (function () {
    return {
        init: function () {
        },
        displayPopUpWindow: function (firstName, lastName) {

            var postData = {
                firstName: firstName,
                lastName: lastName
            };

            $.post("/Setup/GetNewAccountViewHtml", postData, function (data) {
                $.telerik.window.create({
                    title: "Sample Window",
                    html: unescape(data.viewHtml),
                    modal: true,
                    resizable: false,
                    visible: false,
                    width: 500,
                    height: 200
                })
            .data('tWindow').center().open();
            });
        }
    };

})();

$(document).ready(function () {
    AccountSetupForm.init();
});

So for a full view on how this is structured, please refer to the image below. I highlighted what was used on the codes above.

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
New Zealand New Zealand
http://nz.linkedin.com/in/macaalay
http://macaalay.com/

Comments and Discussions

 
QuestionGetAccountViewModel Method Pin
Member 1224515619-Oct-16 4:12
Member 1224515619-Oct-16 4:12 
QuestionWhat is the point of RenderRazorViewToString? Pin
Cookiesworld31-Mar-15 5:01
Cookiesworld31-Mar-15 5:01 
GeneralMy vote of 2 Pin
Islam Kareem28-Nov-14 20:19
Islam Kareem28-Nov-14 20:19 
Questionhow to do unittest RenderRazorViewToString(string viewName, object model) ? Pin
Member 1005369227-Jun-14 9:53
Member 1005369227-Jun-14 9:53 
Question[My vote of 1] No sample project Pin
msdevtech22-Nov-13 7:41
msdevtech22-Nov-13 7:41 
QuestionMessage Closed Pin
31-Jan-13 13:18
WebMaster31-Jan-13 13:18 
AnswerRe:please use the proper words Pin
Jibesh31-Jan-13 14:11
professionalJibesh31-Jan-13 14:11 
SuggestionRE: How to render MVC View on a Modal Popup Window Pin
MiguelCouto17-Jan-12 23:01
MiguelCouto17-Jan-12 23:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.