ASP.Net MVC Modal Dialog

by Weifen Luo (DevZest) 15. May 2013 21:19

Download source code from CodePlex

Currently I’m working on a project using ASP.Net MVC, which is my first ASP.Net MVC project. What really surprises me is, although ASP.Net MVC has been years old, there is no neat solution to open/close modal dialog. Here are some of the google search results with “ASP.Net MVC Modal Dialog”:
StackOverflow: ASP.NET MVC modal dialog/popup best practice
StackOverflow: MVC C# modal popup
Codeproject: A Comparison of Three jQuery Modal Dialogs for ASP.NET MVC

All the proposed solution has some JavaScript you need to copy, paste and modify. You must be kidding me: copy/paste/modify code in the second decade of 21st century? After couple of days hard work since I’m brand new to this area, I finally came up with a solution that can at least satisfy myself.

The demo application has just one link on the main page, which you can click to open the first dialog (Dialog1). In Dialog1, you can also click a link to open the second dialog (Dialog2), and finally Dialog3. On each dialog you can enter the integer number (1 for Dialog1, 2 for Dialog2, 3 for Dialog3) to test data validation:
image

Step by step walkthrough

  1. Create a “Basic” MVC4 application project named “MvcModalDialog” in Visual Studio 2012;
  2. Add the file \Scripts\modaldialog.js and \ModalDialogExtensions.cs to the project. This is where the solution is implemented and we will discuss it later;
  3. Modify \web.config and \Views\web.config to add namespace “MvcModalDialog”, otherwise you have to put a “@using MvcModalDialog” on each page;
  4. Including css and scripts in \Views\Shared\_Layout.cshtml:
    <!DOCTYPE html>
    <html>
    <head>
        ...
        @Styles.Render("~/Content/themes/base/jquery.ui.all.css")
        @Styles.Render("~/Content/themes/base/jquery.ui.dialog.css")
        ...
    </head>
    <body>
        ...
    @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryui") @Scripts.Render("~/bundles/jqueryval") ...
    </
    body> </html>
  5. The Model (\Models\DialogModel.cs):
        public class DialogModel
        {
            [Required]
            public int Value { get; set; }
        }
  6. The Controller (\Controllers\HomeController.cs, please pay attention to the comment):
    public class HomeController : Controller
    {
        ...
    public ActionResult Dialog1() { return PartialView(); } [HttpPost] public ActionResult Dialog1(DialogModel model) { return ProcessDialog(model, 1, "Great, your answer is correct!"); }


    ...
    ActionResult ProcessDialog(DialogModel model, int answer, string message) { if (ModelState.IsValid) { if (model.Value == answer) return this.DialogResult(message); // Close dialog via DialogResult call else ModelState.AddModelError("", string.Format("Invalid input value. The correct value is {0}", answer)); } return PartialView(model); } }
  7. The View (\Views\Home\Dialog1.cshtml, please pay attention to the comment):
    @model MvcModalDialog.Models.DialogModel
    
    @using (Ajax.BeginModalDialogForm())    // Modal dialog form
    {
        @Html.ValidationSummary()
    
        <fieldset>
            <legend>Dialog1</legend>
            <p>Please enter interger 1. Enter other value to see the validation errors.</p>
            @Html.LabelFor(m => m.Value)
            @Html.TextBoxFor(m => m.Value)
            <p>
                @Ajax.ModalDialogActionLink("Click to open dialog2", "Dialog2", "Dialog2")  // Action link to open dialog
            </p>
            <input type="submit" value="OK" />
        </fieldset>
    }
  8. That’s it! Your application is ready to run!

    How does it work

    The extension helper method ModalDialogActionLink, BeginModalDialogForm generates html markup that can be executed by the JavaScript defined in modaldialog.js. For example, the ModalDialogActionLink code in \Views\Home\Index.cshtml:

        @Ajax.ModalDialogActionLink("Please click to open the modal dialog", "Dialog1", "Dialog1")
    

    will generate the following markup (use “View Source” in your browser):

    <a data-ajax="true"
       data-ajax-begin="prepareModalDialog(&#39;18678182-d4a2-49eb-a1cf-843cc06f6d54&#39;)"
       data-ajax-failure="clearModalDialog(&#39;18678182-d4a2-49eb-a1cf-843cc06f6d54&#39;);alert(&#39;Ajax call failed&#39;)"
       data-ajax-method="GET"
       data-ajax-mode="replace"
       data-ajax-success="openModalDialog(&#39;18678182-d4a2-49eb-a1cf-843cc06f6d54&#39;, &#39;Dialog1&#39;)"
       data-ajax-update="#18678182-d4a2-49eb-a1cf-843cc06f6d54"
       href="/Home/Dialog1">Please click to open the modal dialog</a>

    The ModalDialogActionLink method generates a new GUID and use it as parameter of prepareModalDialog, clearModalDialog and openModalDialog JavaScript function, which are defined in modaldialog.js.

    You can check the source code to find out the details – it’s less than 100 lines of code in total. The whole point is using extension helper method to encapsulate the implementation details, making the solution clear and neat.

Tags:

.Net | ASP.Net | ASP.Net MVC | JQuery | JavaScript | Code Sample

Comments

Comments are closed

Copyright DevZest, 2008 - 2014