I am in the process of creating a prototype project using MVC 3 and I have come across a situation which I can\'t seem to find an answer for and it seems like I might be app
I came across something interesting when working with nested partial views in MVC4. Just in case somebody stumbles upon this..
When rendering a partial view in a loop,
@Html.Partial()
does not work.
Instead, use @Html.RenderPartial();
that emits the HTML instead of HTML encoded in the former case and works.
Cheers!
I have found a solution which incorporates both @Roman Mazur and @Mohayemin's answers with an AJAX call.
I changed my View to the following as Roman suggested:
public PartialViewResult List() {
return PartialView();
}
I then changed the section to a div as Mohayemin suggested:
<div id="adminmain"></div>
I then created a link that invokes an AJAX script on it's click event:
<li><a id="load-partial">CONTACTS</a></li>
<script>
$(document).ready(function () {
$('#load-partial').click(function () {
$.ajax({
url: '/Contact/List/',
datatype: 'html',
success: function (data) {
$('#adminmain').empty().html(data);
}
});
});
});
</script>
It works well, but I am always open to more suggestions on how to improve it.
Thanks very much.
Convert
From
<section id="adminmain">
@RenderBody()
</section>
To
<div id="adminmain"></div>
From
@Html.ActionLink("Contact", "List", "Contact")
To
@Ajax.ActionLink("Contact", "List", "Contact", new AjaxOptions { UpdateTargetId = "adminmain" })
And in ContactController
List
action return PartialView()
instead of 'View()'.
Do not forget to include jquery.unobtrusive-ajax
in your view to make Ajax
work.
And before all read Roman's Answer
You can not use @RenderBody()
multiple times. One @RenderBody()
in your main _Layout file is fair enough. In your second view use instead @RenderPartial()
or @RenderAction
.
UPDATE (based on first comment)
Let's say you want to render /Administrator/TheAction
, so you will call
@{
Html.RenderAction("TheAction", "Administrator");
}
TheAction
action will look like this:
public PartialViewResult TheAction() {
return PartialView();
}
And it will render the view in ~/Views/Administrator/TheAction.cshtml
right inside the place from which you called the RenderAction()
.
The importance is that it does not accomplish another @RenderBody
. As you can see in TheAction()
example, you are returning PartialViewResult, which does not have any @RenderBody()
helper.