Skip the talk ? Download Source Code

Firstly you will need to import the following jquery and css files, best practice would be to import these files into the _Layout.cshtml

Imports

<head>  
<title>@ViewBag.Title</title>  
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />  
<link href="@Url.Content("~Content/themes/base/jquery.ui.all.css") rel="stylesheet" type="text/css" />  
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>  
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>  
</head>  

Now lets dig in to the Jquery code required for the modal popup to work.

Jquery code

<script type="text/javascript">

$.ajaxSetup({ cache: false });

$(document).ready(function () {  
    $(".openDialog").live("click", function (e) {  
        e.preventDefault();

    $("<div></div>")  
        .addClass("dialog")  
        .attr("id", $(this)  
        .attr("data-dialog-id"))  
        .appendTo("body")  
        .dialog({  
        title: $(this).attr("data-dialog-title"),  
        close: function () { $(this).remove(); },  
        modal: true,  
        height: 250,  
        width: 400,  
        left: 0

    })  
    .load(this.href);  
    });

    $(".close").live("click", function (e) {  
        e.preventDefault();  
        $(this).closest(".dialog").dialog("close");  
    });  
});  
</script>

In the ActionLink defined below we are using the following 3 properties,

  • class – indicates that on click of this link, execute the jquery written above
  • data_dialog_id
  • data_dialog_title – Used to display the title of the jquery modal popup

Razor code

@Html.ActionLink("Open Jquey Modal Popup", "About", "Home",null,new {  
@class = "openDialog",  
data_dialog_id = "aboutDialog",  
data_dialog_title = "About Us"  
})  

Below is the ‘About’ action of the ‘Home’ controller which will be called when a user clicks on the above ActionLink.

Controller

public ActionResult About()  
{  
    return View();  
}  

Below is the About.cshtml view which will be display by the above (About) action. Note that I have set the layout to null, so that I dont get duplicate master template showing up on each other.

About.cshtml view

@{  
    ViewBag.Title = "About Us";  
    Layout = null;  
}

<h2>About</h2>  
<p>  
Hello, this is a modal jquery popup !  
</p>  
<p><a href="javascript:void(0);" class="close">Close this Window</a></p>

And your done ! Yes seriously ! below are the screenshots on how the modal popup appears at runtime.

Output

[click to enlarge]

You can download the source code from this link