Friday, September 28, 2012

Loading Modals via Twitter Bootstrap plus ASP.NET/MVC/C#

I ran into a little snag trying to implement Twitter Bootstrap within an ASP.NET/MVC/C# site, as the modal functionality does not play so nicely with ASP.NET and the MVCContrib Grid.

Step 1: Add code for the Modal into the page that will launch the modal.

<div id="modalWindow"><div id="modalContent"></div></div>


Step 2: Add the javascript code to lauch the modal when the button is clicked.  JQuery will get the url in the data-vals attribute, and load the content into the modal window.

$(".modalButton").click(function () {
        //get the URL from the data-vals attribute, and display the
        //data in a modal
        var url = $(this).attr('data-vals');
        $.get(url, function (data) {
            $("#modalContent ").html(data);
            $("#modalWindow ").modal(show = true, backdrop = false);
        });

    });



Step 3: Add a controller action to get the view for the modal.  The specifics were left out, but this should return the data to be displayed in the modal.

  public ActionResult Edit(Guid id)
        {

               //Populate the Model...or not, depending on yours needs
               return View(Model);
        }


Step 4: Add a new MVCHtmlHelper to generate the correct hyperlink tag within the MVCContribGrid.  This will basically rename the href attribute to "data-vals" and the "data-modal" attribute to href.  I saw examples online where both attributes were named href, but I couldn't get this configuration to work with the MVCContribGrid.

public static MvcHtmlString ModalLink(this HtmlHelper htmlHelper, MvcHtmlString actionLinkFunction)
        {
            var sb = new StringBuilder(actionLinkFunction.ToString());
            sb.Replace("href", "data-vals");
            sb.Replace("data-modal", "href");

            return new MvcHtmlString(sb.ToString());
        }



Step 5: Use the new MVCHtmlHelper with the MVCContribGrid

        .Columns(column =>
        {
            column.For(c=>@Html.ModalLink(Html.ActionLink("Edit", "Edit", "Admin", new { id = c.UserId }, new { @class = "btn modalButton", data_modal="#modalWindow", data_toggle="modal" }))  

        }

Step 6: Add the Twitter bootstrap markup to the view that will display in the modal.

<div class="modal-header">  
   <button type="button" class="close" data-dismiss="modal">×</button>  
   <h3>Name</h3> 
</div>  
<div class="modal-body"> BODY </div> 
 <div class="modal-footer">  
     <a href="#" class="btn" data-dismiss="modal">Cancel</a>  
     <a href="#" class="btn btn-primary">Save</a> 
</div>

And that's it!  I am seeing an issue where the background layout gets a bit wacky after the modal is loaded.  I'm working on a fix.  :)

Reference


   

No comments:

Post a Comment