Using Bootstrap Modal window as PartialView
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='@Url.Action("GetGameListing")'> <div id='gameContainer'> </div></div><button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() { $('#showGame').click(function() { var url = $('#gameModal').data('url'); $.get(url, function(data) { $('#gameContainer').html(data); $('#gameModal').modal('show'); }); });});
With a method on your controller that looks like this..
[HttpGet]public ActionResult GetGameListing(){ var model = // do whatever you need to get your model return PartialView(model);}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate"> <%Html.RenderPartial("Modal");%></script>
...which lets me keep my templates in a partial view called Modal.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <div> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>{{Name}}</h3> </div> <div class="modal-body"> <table class="table table-striped table-condensed"> <tbody> <tr><td>ID</td><td>{{Id}}</td></tr> <tr><td>Name</td><td>{{Name}}</td></tr> </tbody> </table> </div> <div class="modal-footer"> <a class="btn" data-dismiss="modal">Close</a> </div> </div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%> <div data-id="<%=Html.Encode(item.Id)%>" id="modelModal<%=Html.Encode(item.Id)%>" class="modal hide fade"> </div><%}%>
...and make ajax calls with jQuery:
<script type="text/javascript"> var modalTemplate = $("#modalTemplate").html() $(".modal[data-id]").each(function() { var $this = $(this) var id = $this.attr("data-id") $this.on("show", function() { if ($this.html()) return $.ajax({ type: "POST", url: "<%=Url.Action("SomeAction")%>", data: { id: id }, success: function(data) { $this.append(Mustache.to_html(modalTemplate, data)) } }) }) })</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%> <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>"> <%=Html.Encode(item.DutModel.Name)%> </a><%}%>
I have achieved this by using one nice example i have found here.I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.