负载PartialView对AJAX和查看非AJAX请求 [英] Load PartialView for AJAX and View for non-AJAX request
问题描述
我想实现像在Facebook的:
I wanna implement something like in facebook:
- 在左侧点击照片,它通过AJAX加载
- 在中间点击滚动,它通常装有额外的布局
现在我有一个观点,这是在控制器装在两个不同的方法:
For now I have a View, which is loaded in Controller in two different methods:
public ActionResult Overview()
{
return View("Overview");
}
public ActionResult OverviewPartialView()
{
return PartialView("Overview");
}
而在jQuery脚本,它看起来是这样的:
And in jquery script it looks like this:
$(contentContainer).load(_link + 'PartialView');
我的问题是,有没有更好的办法来解决这个问题? 我曾尝试与类似的东西在_ViewStart:
My question is, is there a better way to solve that problem? I have tried with something like that in _ViewStart:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
if (IsAjax)
{
Layout = null;
}
}
和类似的东西在控制器:
And something like that in Controller:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
return PartialView();
return View();
}
不过,在这些解决方案,我曾与缓存的一个问题,布局,布局加载打开一个页面,在AJAX请求也该页面后。
But in those solutions I had a problem with cache, after opening a page with layout, in AJAX request also that page with layout was loaded.
推荐答案
您可以使用一个动作:
public ActionResult Overview()
{
return View();
}
和里面的 _ViewStart.cshtml
:
@{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/Layout.cshtml";
}
另一种可能性是使用以下命令:
Another possibility is to use the following:
public ActionResult Overview()
{
if (Request.IsAjaxRequest())
{
return PartialView();
}
return View();
}
那么,如果你想避免的缓存的问题,你可以使用一个POST请求而不是GET:
then if you want to avoid caching problems you could use a POST request instead of GET:
$.post(_link, function(result) {
$(contentContainer).html(result);
});
或使用 $ AJAX
用GET和指定缓存:假
这将追加一个唯一的查询字符串参数避免浏览器的缓存:
or use $.ajax
with GET and specify cache: false
which will append an unique query string parameter to avoid browsers caching:
$.ajax({
url: _link,
type: 'GET',
cache: false,
success: function(result) {
$(contentContainer).html(result);
}
});
这篇关于负载PartialView对AJAX和查看非AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!