Reputation: 3515
<table>
<tr>
<th>
Author
</th>
<th>
Title
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
@Ajax.ActionLink("View Reviews", "View", new { id = item.ID }, new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.InsertAfter })
</td>
</tr>
}
</table>
<div id="result">
</div>
public PartialViewResult View(int id)
{
ReviewModel reviewModel = new ReviewModel();
return PartialView(reviewModel.GetReviews(id));
}
Upvotes: 2
Views: 9740
Reputation: 239290
Once the response has been sent to the client, the server is done. That means you can't directly have a partial view rendered based on a click, because those are two disjointed processes: a partial view is rendered server-side, while a click is registered client-side, once the server is already out of the picture.
Anytime you're talking about changing the already rendered page in client with some new information from the server, you're talking about AJAX, so you will need to handle that with JavaScript on the client-side, that catches the click event and requests the partial view from the server. That means you'll also need an action, server-side that your JavaScript can send a request to and that returns your partial view.
ReviewsController
public ActionResult View(int id)
{
// fetch reviews for `id`
if (Request.IsAjaxRequest())
{
// return partial for AJAX requests
return PartialView("_ReviewsPartial", reviews);
}
else
{
// return full view for regular requests
return View(reviews);
}
}
Main View
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
@Html.ActionLink("View Reviews", "View", new { id=item.ID }, new { @class = "GetReviewsLink", data_id = item.ID })
</td>
</tr>
}
<div id="SomeDiv"></div>
JavaScript
$(document).ready(function () {
$('.GetReviewsLink').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.get('@Url.Action("View")', { id: id }, function (result) {
$('#SomeDiv').html(result);
});
});
});
That will dump the rendered partial from the server into the div with id, "SomeDiv". You can then display it however you want. For example, you may have a static region that will just switch out the reviews as each item's link is clicked. "SomeDiv" may actually be the inner part of a modal window, that you could then show after the new content has been loaded in. However you want to handle the display.
Upvotes: 5