How to generate the proper url when rendering partial view through ajax in asp.net mvc 3?
my problem is such that i'm trying to create a blog using as much ajax as i can so instead of rendering full views, everytime a user clicks on a navigation link a partial view generates trough ajax call but my url does not change, and when i manually type home/blog only partial view generates the html and no main layout..
this is my controller:
public ActionResult Blog()
{
var rep = repository.FindAllPosts().ToList();
return PartialView(rep);
}
this is my Blog View:
@model IEnumerable<SpongleMVC.Models.Post>
@if (User.Identity.Name == "alanik")
{
<div id="adminPostPanel">
@Ajax.ActionLink("Create Post", "CreatePost", new AjaxOptions()
{
UpdateTargetId = "main"
})
开发者_如何学C</div>
}
@Html.Partial("_PartialPostList", (System.Collections.IEnumerable)Model)
and this is the ajax call in my layout page to open the Blog partial view:
@Ajax.ActionLink("Blog", "Blog", new AjaxOptions()
{
UpdateTargetId = "main"
})
That's the whole point with AJAX. Urls do not change. If you change them the browser redirects. You could implement a solution using url fragments (#
). You could manipulate the url after the #
sign without redirect. This allows to handle history with AJAX. There are also plugins for jQuery such as this one that might enable history with AJAX calls and as a consequence the Back/Next buttons.
If you want your application also to work without AJAX you could test in your controller action whether the request was done using Ajax (Request.IsAjaxRequest()
) and return a full view instead of a partial. So if a user types directly the url in hist browser he will see a full page with a layout and not only a partial.
UPDATE:
I suspect that your Ajax.ActionLink doesn't work as expected because you forgot to include the following script:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
That's what will make those Ajax.* helpers perform Ajax requests in an ASP.NET MVC 3 application.
You shouldn't do it like that.
From a SEO point of view as well as a user's it's horrible navigation.
I would load blog posts as separate pages, so spiders can follow your links and users and other websites can link directly to your posts.
Use AJAX wisely, don't try to make everything AJAX driven.
精彩评论