Graciously Hosted by MaximumASP        

Implementing a jQuery Modal Window in ASP.NET

I’ve recently had several questions about attempts to use the Ajax Control Toolkit’s Modal Dialog, or more accurately, to misuse it, as a window.

It’s a “dialog” and therefore not well suited to being used for receiving data from the user.

Controls like the Modal Dialog Extender Control are convenient when they do when we want them to do but when they don’t there is no reason not to “roll our own” functionality.

In this case I’ve built a sample using jQuery to display a Semi-Modal Window to allow the user to edit a field on the page.

I say “semi” Modal because clicking outside the Window causes the edits to be aborted, the Window to be closed, and the page to be visually restored.

The page normally looks like this…….

jqModal

Then Clicking on the “Edit Photo Caption” link causes this to happen.

jqModal-EditMode

In this dialog one can edit the caption that appears below the photo.

The interesting thing here is that, though I’m using jQuery to display the Window, the rest is plain ASP.NET server controls and code behind.

The “Save” button is an ASP.NET button control which means that there is a Server-Side event handler where I can process they newly entered Photo Caption.

In the case of this demo I just update the page display but we could also use that Click event handler to persist the changed data to a database since it runs server side. (No “services” required.)

 

The Code…

I start with generating a default ASP.NET 4 Web Forms Application with Visual Studio 2010

Then we pull jQuery via a reference in the master page.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

 

 

Note that the new Web Forms project template in Visual Studio 2010 includes versions of jQuery and even one that has IntelliSense support but I’ve opten to dynamically bull the latest version directly from the jQuery code repository.

Next, we have some styles added to the generated Style.css file to handle making the page opaque when we show the Window as well as styles for the Window itself.

 

   1: #mask 
   2: {
   3:   position:absolute;
   4:   left:0;
   5:   top:0;
   6:   z-index:9000;
   7:   background-color:grey;
   8:   display:none;
   9: }
  10:   
  11: #boxes .window {
  12:   position:absolute;
  13:   left:0;
  14:   top:0;
  15:   width:440px;
  16:   height:200px;
  17:   display:none;
  18:   z-index:9999;
  19:   padding:20px;
  20: }
  21:  
  22: #boxes #modalwindow {
  23:   width:375px; 
  24:   height:203px;
  25:   padding:10px;
  26:   background-color:#ffffff;
  27: }
  28:  
  29: .stylecenter
  30: {
  31:     text-align: center;
  32: }

 

Next we have the code for displaying the Window. Note that this jQuery code is bound ONLY to a DOM <A> Element named “modal”.

Lets look at the code and then I’ll call out a detail or two.

   1:      <script type="text/javascript">
   2:          $(document).ready(function () {
   3:   
   4:              // Set up for displaying modal dialogs
   5:              $('a[name=modal]').click(function (e) 
   6:              {
   7:                  // Prevent the default link behavior of navigation so we can 
                                                               use the link to show the Window
   8:                  e.preventDefault();
   9:   
  10:                  // Determine which href was clicked if it was in fact an href
                                                               (though this demo as only one.) 
  11:                  var id = $(this).attr('href');
  12:   
  13:                  // Determine browser windows dimensions. 
  14:                  var maskHeight = $(document).height();
  15:                  var maskWidth = $(window).width();
  16:   
  17:                  // Set dimensions for the mask to opaque the screen when the modal 
                                                                        window is displayed.
  18:                  $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
  19:   
  20:                  // Make the Window Opaque        
  21:                  $('#mask').fadeIn("fast");
  22:                  $('#mask').fadeTo("slow", 0.8);
  23:   
  24:                  //Get the window height and width
  25:                  var winH = $(window).height();
  26:                  var winW = $(window).width();
  27:   
  28:                  // Set the Modal Window's dimensions to center in the browser window.
  29:                  $(id).css('top', winH / 2 - $(id).height() / 2);
  30:                  $(id).css('left', winW / 2 - $(id).width() / 2);
  31:   
  32:                  // Show the Modal Window
  33:                  $(id).fadeIn("fast");
  34:   
  35:              });
  36:   
  37:              // Handle Close Button Click Event
  38:              $('.window .close').click(function (e) {
  39:                  // Cancel the link behavior
  40:                  e.preventDefault();
  41:   
  42:                  $('#mask').hide();
  43:                  $('.window').hide();
  44:              });
  45:   
  46:              // The user clicks OUTSIDE the Modal Window and the window will be closed without save.
  47:              $('#mask').click(function () {
  48:                  $(this).hide();
  49:                  $('.window').hide();
  50:              });
  51:   
  52:          });
  53:  </script>

We should also note the HTML for the like and the Window to be shown when that like is clicked.

<a href="#modalwindow" name="modal">Edit Photo Caption</a>
</div>
<div id="boxes">
    <div id="modalwindow" class="window">
        <center>Enter New Caption</center><br />
        <asp:TextBox ID="ClientDataTextBox" runat="server" ClientIDMode="Static" TextMode="MultiLine" 
                                                           Height="120" Width="370"></asp:TextBox><br /> 
        <asp:Button ID="ModalButton" runat="server" Text="Save" onclick="ModalButton_Click" />               
    </div>
    <!-- Mask to cover the whole screen -->
    <div id="mask"></div>
</div>

 

Note the line …..

$('a[name=modal]').click(function (e) 

“modal” is the name of the <A> object that for opening the Window.
 
Note that the href= is set to the same name as the id of the <DIV> to be displayed when the <A> is clicked and it is that relationship that causes the related Window to be displayed.
 
The cool thing about this is (to me anyway) how I can intermingle ASP.NET and jQuery JavaScript. The fields in the Modal Window get processed in my Code-Behind so I don’t need to write extra JavaScript to fetch and handle the new Photo Caption and I don’t need to write Ajax service Methods to handle Server Side processing of that new data,
 
For me it is this sort of change in style that is indicative of the “new” ASP.NET Web Forms developer.
 
You can grad a zip file of the ASP.NET 4 project [ HERE ]
 
Have Fun !
 
PS: I adapted code from this post http://www.queness.com/post/77/simple-jquery-modal-window-tutorial  to ASP.NET and Failed to give attribution to the original author.  My apologies to Queness.
 

» Similar Posts

  1. Session Time Out Tricks
  2. Using the ASP.NET AJAX Editor Control to Implement In-Place Content Editing.
  3. Proving the performance of Static Properties.

» Trackbacks & Pingbacks

  1. This post was mentioned on Twitter by MisfitGeek: New blog post: http://tinyurl.com/yccb86c - Implementing a jQuery Modal Window in ASP.NET

    Social comments and analytics for this post — January 20, 2010 11:49 PM
  2. Pingback from Implementing a jQuery Modal Window in ASP.NET : Misfit Geek

  3. Pingback from Implementing a jQuery Modal Window in ASP.NET | I love .NET!

  4. Modal Poup Window Using jQuery

    Modal Poup Window Using jQuery — January 21, 2010 8:29 AM
  5. Thank you for submitting this cool story - Trackback from DotNetShoutout

  6. jQuery Modal Window in ASP.NET

    jQuery Modal Window in ASP.NET — January 21, 2010 9:22 PM
  7. You are voted (great) - Trackback from WebDevVote.com

  8. 9efish.感谢你的文章 - Trackback from 9eFish

  9. Ľubilo by sa jquery modálne okno v asp.net ? misfitgeek.com/.../implementing-a-

» Comments

  1. Peter Benson avatar

    Thanks for the post.

    Does this support iframe model (new webpage)?

    Peter Benson — January 21, 2010 2:51 AM
  2. Amr ElGarhy avatar

    Nice post, very clean implementation for a modal window, also thanks for reminding me about the name attribute for the anchor tag, its very useful.

    Amr ElGarhy — January 21, 2010 2:58 AM
  3. Dave avatar

    Or you could just use one of the many jQuery plugins

    e.g. jqueryui.com/.../dialog http://malsup.com/jquery/block/#dialog

    Dave — January 21, 2010 3:22 AM
  4. Phil avatar

    Also achievable with ASP.NET modalPopupExtender, a tiny bit of javascript, and a dummy button, always interesting to know the alternatives though.

    Phil — January 21, 2010 7:40 AM
  5. Salman Farsi avatar

    Good post...

    Salman Farsi — January 21, 2010 7:59 AM
  6. uhs avatar

    Nice one man ! As always made it look so easy ! cheers

    uhs — January 21, 2010 9:25 AM
  7. David Jacob Jarquin avatar

    You have to try Jquery BlockUI malsup.com/.../block

    David Jacob Jarquin — January 21, 2010 4:48 PM
  8. Aaron Schnieder avatar

    Use the jQueryUI dialog... why roll your own? jqueryui.com/.../dialog

    Aaron Schnieder — January 21, 2010 5:34 PM
  9. jQuery Advice avatar

    Store the $(...) result in a variable instead of constantly looking up the same elements over and over again. Otherwise you're looking the element up in the DOM over and over again which isn't free no matter how simple the expression passed to $(...) may be. Most notable in your example are the repeated calls to $(id).

    jQuery Advice — January 21, 2010 7:43 PM
  10. Marcel Wijnands avatar

    Nice, but 2 notes:

    - Doesn't work correctly when you have a page with more content, and you scroll down a little. You could use position: fixed; but that doesn't work in IE6, so you should do a little math with $(window).scrollTop.

    - I wouldn't abuse the name attribute as a selector for this. Instead I'd use a class. The name attribute has other uses, and the class attribute can have multiple (space-seperated) values so using that can never be a problem.

    Marcel Wijnands — January 21, 2010 9:57 PM
  11. Joe Stagner avatar

    Cool - thansk for the tweeks and comments

    Joe Stagner — January 22, 2010 8:16 AM
  12. Salman Farsi avatar

    I use it and get the best result for different browsers like IE 7, IE 8, FireFox 3.0, FireFox 3.5, Google Chrome, Safari, but it is not showing proper in IE 6.

    Can anyone help me...

    Salman Farsi — January 22, 2010 1:22 PM
  13. Calabonga avatar

    thks David Jacob Jarquin, that's I need!!!

    Calabonga — January 22, 2010 6:05 PM
  14. Joe Stagner avatar

    Thanks David,

    jQuery BlockUI looks awesome !

    malsup.com/.../block

    Joe Stagner — January 22, 2010 6:45 PM
  15. Sam avatar

    Joe,

    Thanks for this tutorial and all the other great stuff you've been doing.

    Here's a request: can you do a tutorial where I can use jQuery for a modal window/dialog where the user enters something into the form and server side code processes the data and sends results of the data back to to modal window. A good example is some type of lookup like search engine results.

    Thanks,

    Sam

    Sam — January 24, 2010 11:39 AM

Comments are closed