Add Jquery modal dialogs to ASP.NET MVC Views

Setup ASP.NET MVC environment

Let’s find out how to add JQuery popup dialog box to ASP.NET MVC Razor view. We assume you have setup necessary MVC3 environment. If not visit ASP.NET official website and download necessary components for your development environment. For this article I’ve used Visual Studio 2010. Open your developer environment and create a new ASP.NET MVC application. You can create an empty application. Once you create the application you can notice MVC3 adds few folders into your solution structure. Let’s dig into two folder sets that marked in green.

how mvc3 solution structure looks like

Scripts folder, is the most important folder for ASP.NET MVC applications. This will hold all the required JQuery and Javascripts by the MVC application to run. We are not going into details of each of these files, but for the moment we need two files. Those are jquery-1.5.1-min.js and jquery-ui-min.js. These files names and versions may change based on your new updates. Jquery-min.js is the core library of Jquery. It adds the core functionality of Jquery into your ASP.NET MVC3 view when you reference it.  Jquery-ui.js is the file responsible for all the UI functionality such as Dialogs, Popus, Drag and drop, Calenders etc. You can check what is available with JQuery UI visit here

As you know content folder will hold all the themes, style sheets and images required to style the site. By default ASP.NET MVC adds a theme call base theme. In this base theme folder it will place Jquery UI style sheet and the images. If you want more information about JQuery UI please visit there official website.

Set Jquery reference in ASP.NET MVC

In order to create Jquery UI dialog box, we need to refer required files. In ASP.NET MVC when you run your MVC application it starts with _viewStart.cshtml in the views folder. In this file you will find that it refers to the default _Layout.cshtml in the shared folder. This _Layout.cshtml file will be your default master page. All the Razor views will inherit this master page unless if you explicitly remove the reference. So the best place to set your style sheet and Jquery references will be _Layout.cshtml. You can set your references as follows;

Create ASP.NET MVC Controller

Lets create a Razor view. Before you create a view you need to create a controller. Lets create a controller call homeController.cs in controllers folder.  You can create a controller as follows;

Once you create the homeController.cs you controller code will look like as follows;

Create ASP.NET MVC razor View

By default it adds the index action method. Now you can create a empty view using this action method. All what you have do right click on the return view then you will get a popup as follows;

Now click add view. You will get another screen to set settings for the view. It is as follows;

Click Add. Two things will happen. It will create a new folder in the views folder call home and add a view index.cshtml. Your index view will look like as follows;

Now you are ready to run and view what you have created so far. Once you run this ASP.NET MVC application you will get a screen saying Index. If you check the html source you can notice your Jquery and Style sheet references are there in place.

Adding JQuery UI Dialog

Lets add a html link and a hidden div tag into the index view, saying simple dialog as follows;

<a href="#" id="simpledialog">Simple Dialog</a>
<div id="dialogbox" style="display:none;"> Your first Dialog box!</div>

When users trigger click event of this link we can show the hidden div as a simple dialog box. To create this dialog box you need to add following Jquery code into your view.

<script type="text/javascript">
 $(document).ready(function () {
    $("#simpledialog").click(function () {
       $("#dialogbox").dialog();
    });
 });
</script>

Now when you refresh the browser and click on the simple dialog box link it will crate a very basic dialog box like below;

As you can see the dialog is missing a title. Two ways to add title to dialog box. The first way will be adding a title attribute to the dialog div tag as follows;

<div id="dialogbox" style="display:none;" title="Dialog title"> Your first Dialog box!</div>

Jquery Ui will pickup div title tag as the title of the dialog. The other way will be pass the title as a dialog parameter as shown below;

<script type="text/javascript">
 $(document).ready(function () {
   $("#simpledialog").click(function () {
     $("#dialogbox").dialog({title:"Dialog Title one"});
   });
 });
</script>

Dialog parameters are the most important part of Jquery Dialog. Passing different parameters to dialog you can get different outputs. For all the allowed parameters visit JQuery Wiki.

Add Buttons to JQuery Dialog box

Lets add some more features to the dialog box. You can add buttons by passing the button parameters. Below code will show how to add two buttons to the JQuery dialog.

<script type="text/javascript">
 $(document).ready(function () {
   $("#simpledialog").click(function () {
     $("#dialogbox").dialog({ title: "Dialog Title one", buttons: {
       "OK": function () {
          alert("Ok clicked");
          $(this).dialog("close");
      },
       "Cancel": function () {
          alert("Cancel clicked");
          $(this).dialog("close");
      }
    }
   });
 });
 });

</script>

Once you view it on the browser you will get a popup with two buttons and each will have it’s own click event handler. You can add any amount of buttons based on your requirement.

Positioning the JQuery Dialog box

One more important option will be positioning the dialog box. By default it will be placed center of the screen. But by passing the position parameter values you can position any place you want. Below code shows how to position the dialog;

<script type="text/javascript">
 $(document).ready(function () {
   $("#simpledialog").click(function () {
      $("#dialogbox").dialog({
        title: "Dialog Title one",
        position:[50,50],
        buttons: {
          "OK": function () {
          alert("Ok clicked");
          $(this).dialog("close");
        },
       "Cancel": function () {
       alert("Cancel clicked");
      $(this).dialog("close");
      }
    }
   });
 });
 });

</script>

How to remove close button from the JQuery Dialog

Sometimes you may need the user to select the option buttons provided in the dialog box. In such situations you may need to remove the “x” close button from the title bar. For this we have to use the open event. When open event fire we are hiding the button using class name. Following code shows how to remove close button;

<script type="text/javascript">
 $(document).ready(function () {
   $("#simpledialog").click(function () {
    $("#dialogbox").dialog({
      title: "Dialog Title one",
      position: [50, 50],
 open: function(event, ui) { $(".ui-dialog-titlebar-close").hide();},
     buttons: {
     "OK": function () {
     alert("Ok clicked");
     $(this).dialog("close");
     },
     "Cancel": function () {
     alert("Cancel clicked");
     $(this).dialog("close");
    }
   }
  });
 });
 });

</script>

On the browser it will look like as follows;

There are many more options which you can use to play around and use it for your development.

16 thoughts on “Add Jquery modal dialogs to ASP.NET MVC Views

  1. Alana

    I followed your code directly and added it to a mvc 4 application I am working on but when I click on the simple dialog link I keep getting an error saying “0x800a01b6 – Microsoft JScript runtime error: Object doesn’t support property or method ‘dialog’” any idea why this is happening and what I may be missing. I am pretty new to coding but I don’t understand why its not working. Please get back to me as soon as you can. Thank you in advance.

    1. admin

      Hi Alana,
      I’m sure this is something to do with the JQuery references. here are few thins that you can do;
      1. Try to update the JQuery script files using NUget and make it up to date.
      2. Then check without any MVC code, when you click on a link/Button Jquery dialog is working or not.
      3. if nothing works you can post your code here. it will be helpful to give a fix

      The same code I’m using in the MVC4 applications.
      Thanks

        1. Alana

          Great thanks so much for your reply. I updated my Jquery script files and then it worked! however is there a way to change the color of the title bar? I want it to match the headers and theme of my site. Im not sure if this would this be done in css or added to the jquery code?
          Thank you!

    1. admin

      Hi Alan,
      You can simple change the size of the Jquery dialog by passing following parameter into dialog function

      $(“#selector”).dialog({width : “500px”});

      if you want to give the height can do as follows;

      $(“#selector”).dialog({width : “500px”, height : “200px”});

      Hope this will help…

      1. Alana

        for some reason i cant get the size to change with the code you provided. do i need to include something else? I am using a asp.net mvc 4 application.

        also i would like to have an affect that darkens the background of the page when the dialog box is displayed. do you know of a way to do this?

        thanks so much
        Alana

        1. admin

          Hi Alana
          MVC4 has nothing to do with the dialog box. I suspect that you have pass the width parameter incorrectly. Let me guide you to the correct way. Please look at the below code;
          $("#popup").click(function () {
          $('#popupbox').dialog({width:"500px", title: "Sample popup box", modal: true, buttons: {
          "OK": function () {
          alert("Ok clicked");
          $(this).dialog("close");
          },
          "Cancel": function () {
          alert("cancel clicked..!");
          $(this).dialog("close");
          }
          }
          });

          });
          Make sure each parameter to be separated with a comma. Above code works well and it will make your dialog 500px width.

          For the second question background color of the dialog box. It is call the overlay of the modal popup. You can change the color of it by simply adding a overriding style class of your style sheet. Remember the style class should come after the jQuery UI css.

          You can use below css code to change the color of the overlay;


          .ui-widget-overlay {background-image:none; background-color:red; opacity:0.03; filter: "Alpha(Opacity=100)";}


          You need to set the color value you want to the background-color property. If you feel color is dark or light then make
          adjustment to opacity and filter properties.

          Hope this will help

  2. Alana

    sorry to keep asking so many questions but how would add that overlay into the code for the dialoag window? i understand adding it in the css file but im assuming it needs to link or call something in the current code creating the dialog….also if I wanted to add in a photo to a dialog box once it is clicked how would that code look? I am really new to all of this so I really appreciate all your help and support.

    1. admin

      Hi Alana,
      Until you clear your doubts you need to clarify. It is alright keep asking questions.

      If you specify the parameter modal:true then JQuery UI dialog will automatically append a overlay div to prevent other areas being accessed by the user. Please refer the Jquery documentation link provided. If you don’t specify the modal property then no overlay with come and while displaying the dialog users can access the other ares of your web page.

      If you want to add a photo to a dialog box, while loading the view you need to update the image link inside the dialog div. It is something like this;

      Assume that your dialog div is as follows;

      <div id="popupdiv" style="display:none">
      <img alt="" src="image location" />
      </div>

      If your image name stored in a DB then you need to use Razor syntax to give the correct image location. To that you can use html helpers to create the image path. Since the div is hidden it would not be visible to users unless they click on the dialog button or link

      If you can post the exact code of yours it would be great.
      Hope this would help

  3. Alana

    This is the code I am using. I got the image to display but I still am not clear on the overlay feature. I just want the webpage background to darken when the dialog box opens. Can you help me add the correct code in to do that?

    Ardent Photos

    $(document).ready(function () {
    $(“#simpledialog”).click(function () {
    modal: true,
    $(“#dialogbox”).dialog({ width: “700px”, title: “Ardent Photos”, });
    });
    });

    Also is there a way to add mulitiple images to the dialog box and have a button to click thru them all?

    Thank you so much for all your help and hope to hear back from you soon.

    1. admin

      Hi Alana,
      The real issue why you are not getting the dialog box overlay is that your modal : true parameter is not within the dialog function. If you look at my previous answers you can cleat it up.

      so the correct code should be as follows;
      $(“#dialogbox”).dialog({ width: “700px”, title: “Ardent Photos”,modal : true });

      Yes you can have multiple images within the Jquery dialog and can slide them left to right or what ever by installing a Jquery image sliders into your code.

      For example you can use a jQuery slider plugin like this or you can select any of these JQuery Image slider Plugins.

      Hope this would help

  4. Alana

    here is the full code, looks like the first post didnt get it all…..thanks

    Ardent Photos

    $(document).ready(function () {
    $(“#simpledialog”).click(function () {
    modal: true,
    $(“#dialogbox”).dialog({ width: “700px”, title: “Ardent Photos”, });
    });
    });

  5. Alana

    $(document).ready(function () {
    $(“#simpledialog”).click(function () {
    modal: true,
    $(“#dialogbox”).dialog({ width: “700px”, title: “Ardent Photos”, });
    });
    });

Leave a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.