I have a site set up in ASP.NET MVC3 right now, but the layout of everything is optimized for mobile devices.
I would now like to combine some of the existing views together to take advantage of the additional screen space in a desktop browser or tablet.
I have two views now, one displaying a list of links and a second displaying some content generated by each link; both these views are handled by separate controllers. Here is the list view (simplified). It uses a layout page, so this is what would be displayed when @RenderBody() is called in the layout (my second view also works like this, with the same layout file).
@model IEnumerable<CommandCenterEntity>
@{
if (Request.Browser.IsMobileDevice) {
Layout = "~/Views/Shared/_LayoutMobileContent.cshtml";
}
else {
Layout = "~/Views/Shared/_LayoutDesktop.cshtml";
}
}
<ul data-role="listview" id="commandcenterlist" data-filter="true" data-inset="true" data-theme="b">
@foreach (var entity in Model)
{
<li>
@Html.CommandCenterLinks(@entity, x => Url.Action("Index", "Worksheet", new { ParentId = @entity.ID_Item }))
</li>
}
</ul>
The CommandCenterLinks helper just generates an “a” tag containing a different icon depending on some properties of the entity.
I’d like to combine my views in such a way that when I click a link in the list, which would be in a div tag on the left of the screen, the generated content will display in a separate div tag on the right.
I was hoping I could reuse the same actions/controllers used in my mobile layout, so I tried using jQuery to intercept the click event on the list and capture the data returned from the action, and inject it into the div:
$(document).on("click", "#commandcenterlist a", function (e) {
$.mobile.showPageLoadingMsg();
$.ajax({
url: this.href,
success: function (data) {
$.mobile.hidePageLoadingMsg();
$("#desktopContentPane").html(data);
}
});
return false;
});
However, the data I get back in the ajax success handler contains the full html page,
<!DOCTYPE html>
<html>
<head>...</head>
<body>...</body>
</html>
…when all I want is the content that would have been generated in the layout’s @RenderBody() call. I tried changing the controller method to have return PartialView("Index");, but it gave the same result. Is there a way for me to get back only that portion of the view? Or is there some cleaner, more “MVC” way of going about this?
The best option is really to return your partial view from a separate controller action. So, a few things I would change to make it work: