這個問題有一個簡單的解決方案。我有部分視圖的索引頁。部分視圖包含指向其他視圖的鏈接列表,「返回列表」鏈接將鏈接列表視爲部分視圖。此外,索引頁面還有jQuery腳本,其中包含可防止頁面重定向並將結果返回到局部視圖的ajax腳本。所以,如果我第一次點擊任何鏈接,結果會顯示在索引頁的部分視圖中。然後我點擊「返回列表」,然後點擊任何鏈接,第二次腳本不工作,頁面重定向。哪裏不對?jQuery只運行一次
下面是一個代碼:
模型 「鏈表」:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AjaxTest.Models
{
public partial class LinkList
{
public int id { get; set; }
public string label { get; set; }
public string method { get; set; }
public string controller { get; set; }
public string htmlLabel { get; set; }
}
}
控制器有以下代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxTest.Models;
namespace AjaxTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult PartialView(int id)
{
ViewBag.Id = id;
return View();
}
public ActionResult PartialsList()
{
List<LinkList> list = new List<LinkList>()
{
new LinkList{id = 1, label = "First partial", method = "PartialView", htmlLabel = "first-partial"},
new LinkList{id = 2, label = "Second partial", method = "PartialView",htmlLabel = "second-partial"},
new LinkList{id = 3, label = "Third partial", method = "PartialView", htmlLabel = "third-partial"}
};
return View(list);
}
}
}
然後3視圖頁面PartialView.cshtml:
PartialsList.cshtml:
@model IEnumerable<AjaxTest.Models.LinkList>
<div>
@foreach (var item in Model)
{
@Html.ActionLink(item.label, item.method, item.controller, new { id = item.id }, new { id = item.htmlLabel })
<br />
}
</div>
而且index.cshtml:
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
jQuery(document).ready(function() {
$('#first-partial').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$('#pview').load(url);
})
$('#second-partial').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$('#pview').load(url);
})
$('#third-partial').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$('#pview').load(url);
})
$('#backToList').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$('#pview').load(url);
})
});
</script>
<h2>Index</h2>
<div id="index">
<fieldset>
<legend>Index</legend>
This is Index page!
</fieldset>
</div>
<div>
<fieldset>
<legend>Partials</legend>
<br />
<fieldset>
<div id="pview">
@Html.Action("PartialsList", "Home", null)
</div>
</fieldset>
<div>
@Html.ActionLink("Back to list", "PartialsList", "Home", null, new { id = "backToList" })
</div>
</fieldset>
</div>
「這個問題有一個簡單的解決方案。」 –