You can use bootstrap modal dialog with ajax to load the details/view partial view result to the modal dialog.
First, add a new css class to the button, which we will use to wire up the click event later to fire up the modal dialog. Also we will generate the url to the details view using the Url.Action
html helper method and keep that in html5 data attribute in the button(we will use this for our ajax call later)
@foreach (var item in Model.Questions)
{
<tr>
<td>
<button type="button" class="btn btn-success btn-sm modal-link"
data-targeturl="@Url.Action("Details","Home",new { id = item.Id })">
View
</button>
</td>
</tr>
}
Now add the below code to your current view (or even the layout). This will act as the container for our modal dialog.
<!-- The below code is for the modal dialog -->
<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
<a href="#close" title="Close" class="modal-close-btn">X</a>
<div class="modal-content">
<div class="modal-body"></div>
</div>
</div>
Now, let's wire up the click
event on any element with "modal-link" css class. We added this classes to our buttons earlier.
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$("#modal-container").remove();
$.get($(this).data("targeturl"), function (data) {
$('<div id="modal-container" class="modal fade">'+
'<div class="modal-content" id= "modalbody" >'+
data + '</div></div>').modal();
});
});
});
So when user clicks on the button, it reads the value of targeturl
data attribute (which is a URL with the item id value in the querystring) and make an ajax call to that URL. In our case, It will make a call to the Details
action method. So let's make sure that it returns the partial view result (out modal dialog content)
public ActionResult Details(int id)
{
// Get the data using the Id and pass the needed data to view.
var vm = new QuestionViewModel();
var question = db.Questions.FirstOrDefault(a=>a.Id==id);
// To do: Add null checks
vm.Id = question.Id;
vm.Title = question.Title;
vm.Description = question.Description;
return PartialView(vm);
}
And the partial view will have the needed html markup for the modal dialog.
@model YourNameSpace.QuestionViewModel
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<h4>@Model.Title</h4>
<p>@Model.Description</p>
<p>Some other content for the modal </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>