[英]Ctrl+Click on link that renders partial view
我得到了一個使用 AJAX 呈現局部視圖的鏈接。
這是我的鏈接代碼:
<a href="#" onclick="LoadChildCategories(@i.CategoryId,
@i.IsTrading.ToString().ToLower())">@i.Name</a>
這是 LoadChildCategories 函數代碼:
function LoadChildCategories(id, isTrading) {
var link;
if (isTrading === false) {
link = '@Html.Raw(@Url.Action("NonTradingCategories", "Home",
new {categoryId = -1}))';
} else {
link = '@Html.Raw(@Url.Action("ModelList", "Home", new {categoryId = -1}))';
}
link = link.replace("-1", id);
$.ajax({
url: link,
method: 'GET',
success: function(data) {
$("#viewPartial").html(data);
}
});
}
當我在沒有 CTRL 的情況下單擊它時,部分視圖會呈現到我的 div 中。 但是當我用 CTRL 鍵單擊它時,局部視圖會呈現到當前選項卡中,然后在索引頁面打開另一個選項卡。
當我右鍵單擊鏈接並選擇在另一個選項卡中打開它時,當前選項卡沒有任何反應,新選項卡在索引頁面打開。
那么,有什么辦法可以處理嗎?
我找到了很好的解決方案,所以我根據這個解決方案修改了項目: Make an MVC Application into a SPA with AJAX and History.js
1) 使控制器方法返回 View,而不是 PartialView 並添加一行代碼來檢查它是否是 AJAX 請求:
public ViewResult Category(int id)
{
ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
var node = CategoriesHandler.Instance.First(x => x.CategoryId == id);
var childCategories = CategoriesHandler.Instance.Where(x => x.ParentId == node.Id).ToList();
ViewBag.Message = node.Name;
return View(childCategories);
}
2) 像這樣編輯 _ViewStart.cshtml:
@{
Layout = ViewContext.ViewBag.IsAjaxRequest == true ? null : "~/Views/Shared/_Layout.cshtml";
}
3) 准備要通過 AJAX 管理的鏈接:
<a href="@Url.Action("Category", "Intech", new { id = i.CategoryId })" class="ajaxLink" data-href="@Url.Action("Category", "Intech", new { id = i.CategoryId })" data-title="@i.Name">@i.Name</a>
4) 在 _Layout.cshtml 為視圖創建容器
@/*Some layout stuff*/
<div id="bodyContent">
@RenderBody()
</div>
@/*Other layout stuff*/
5)准備這樣的助手javascript文件:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
function navigateToURL(url) {
$('#bodyContent').html('<div class="loader"> </div>');
$.ajax({
type: "GET",
url: url,
dataType: "html",
cache: false,
success: function (data, status, xhr) {
$('#bodyContent').hide();
contentShell.html(data);
$('#bodyContent').fadeIn(500);
},
error: function (xhr, status, error) {
$('#bodyContent').hide();
alert("TEST_Error");
}
});
}
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
if (State.url === '') {
return;
}
navigateToURL(State.url);
});});
6) 不要忘記將您的 javascript 文件包含在包中!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.