Reputation: 19933
I have _Layout.cshtml
, the content is :
...
@RenderSection("MyTitle", required: false)
<div class="innerLR">
<div id="appContent">
@RenderBody()
</div>
</div>
...
When I start the application, I go to this action Home/Index
, the view
public ActionResult Index()
{
return View(new BaseModel { Title = "Testing"});
}
The View Index.cshtml :
@section MyTitle{ @Model.Title }
bla bla bla
At this time it's ok, I see the : Testing + bla bla bla.
Now I call Home/SecondAction
via Ajax when I click on a link, the controller return a PartialView and diplay the content in appContent
div.
I call like this:
$.ajax({
url: 'Home/SecondAction',
type: 'POST',
data: {},
success: function (result) {
$(#appContent).html(result);
}
});
The action is :
public ActionResult SecondAction()
{
return PartialView(new BaseModel { Title = "Other Title" });
}
The SecondAction.cshtml is :
@section MyTitle{ @Model.Title }
bla bla again
Here that's not work, I'd have any error but I can the text from the first action and not :
Other Titla bla bla again
To resume I'd like when I return a PartialView
render a section from the _Layout.cshtml
Thanks,
Upvotes: 2
Views: 322
Reputation: 1039488
You seem to be attempting to update 2 different sections of your DOM after the AJAX call. Once possibility to achieve that is to have your controller action return the rendered result of 2 partials as JSON:
public ActionResult SecondAction()
{
return Json(new
{
section1 = RenderPartialViewToString("_Partial1", null),
section2 = RenderPartialViewToString("_Partial2", new BaseModel { Title = "Other Title" }),
});
}
and your AJAX call could now look like this:
$.ajax({
url: 'Home/SecondAction',
type: 'POST',
success: function (result) {
// TODO: you should of course wrap the contents of section 1 in a div with
// id="section1" in your _Layout.cshtml
$('#section1').html(result.section1);
$('#appContent').html(result.section2);
}
});
Now you are probably wondering where is the RenderPartialViewToString
method coming from? It's coming from here
. Or from here
if you wish.
Upvotes: 2
Reputation: 797
I have seen your code deeply you are calling SecondAction
in $.ajax ie: url: 'Home/SecondAction'
.
But your action method name is IndexPartial
ie:
public ActionResult IndexPartial()
{
return PartialView(new BaseModel { Title = "Other Title" });
}
Please change your $.ajax statement like this:
$.ajax({
url: 'Home/IndexPartial',
type: 'POST',
data: {},
success: function (result) {
$(#appContent).html(result);
}
});
Thanks
Upvotes: 0