当我单击tab
上的“部分视图”元素时,像India
一样单击,则整个视图将得到刷新。我尝试使用Ajax
,但控制权甚至没有击中那里。我在哪里做错了,任何人都可以指导我吗?
控制器
public ActionResult Index()
{
ClsHome model = new ClsHome();
return View(model);
}
public PartialViewResult EmployeeBasedCountry(int CountryId)
{
ClsHome clshome = new ClsHome();
clshome.Country = CountryId;
clshome.countries = CountryFilter(CountryId);
return PartialView("~/Views/Home/_pEmp.cshtml", clshome);
}
查看
@model EmpWebsite.Models.Home.ClsHome
<div id=Partial class="col-md-5">
@Html.Partial("_pEmp")
</div>
部分
@model EmpWebsite.Models.Home.ClsHome
<ul class="nav nav-tabs nav-justified">
<li class="active">@Html.ActionLink("India", "EmployeeBasedCountry", "Home", new {@class = "ActionLinkId", @CountryId = "1" },null)
</li>
<li>@Html.ActionLink("USA", "EmployeeBasedCountry", "Home", new {@class = "ActionLinkId", @CountryId = "2" },null)</li>
</ul>
<div class="tab-content">
<div class="panel">
<table class="table-striped">
<tr class="heading">
<th>
EmpId
</th>
<th>
EmpName
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.EmpId
</td>
<td>
<a>@item.EmpName</a>
</td>
</tr>
}
</table>
</div>
</div>
脚本
$(document).ready(function () {
$('.ActionLinkId').on("click", function () {
debugger;
$.ajax({
url: '@Url.Action("EmployeeBasedCountry", "Home")',
type: "GET",
data: { data }
})
.done(function (partialViewResult) {
debugger;
$("#Partial").html(partialViewResult);
});
});
});
答案 0 :(得分:2)
您为@Html.ActionLink
设置了错误的参数
@Html.ActionLink("USA", "EmployeeBasedCountry", "Home",
new { @class = "ActionLinkId", @CountryId = "2" },
null)
此重载为:linktext, action, controller, routeValues, htmlAttributes
,其中htmlAttributes为null
,因此呈现的<a>
不具有这些属性。
易于检查您的渲染的 html,如下所示:
<a href="/Home/EmployeeBasedCountry?class=ActionLinkId&countryId=2">USA</a>
因此,您的链接没有.ActionLinkId
类,因此不会触发jquery。也很容易检查:
$(function() { alert($(".ActionLinkId").length) });
(或使用浏览器调试器更早)
解决的方法是最后删除null
:
@Html.ActionLink("USA", "EmployeeBasedCountry", "Home", new {@class = "ActionLinkId", @CountryId = "2" })
或根据需要将其拆分
@Html.ActionLink("USA", "EmployeeBasedCountry", "Home", new { @CountryId = "2" }, new {@class = "ActionLinkId" })
答案 1 :(得分:1)
单击链接时,发送了ajax请求,但该链接也执行其操作,并刷新页面。因此,您应该防止浏览器刷新页面(有关更多信息,请参见MDN Docs):
$('.ActionLinkId').on("click", function(e) {
e = e || window.event; // To support old browsers
e.preventDefault();
$.ajax({
url: '@Url.Action("TabLeadingSires", "Home")',
type: "GET",
data: { data }
}).done(function(partialViewResult) {
$("#Partial").html(partialViewResult);
});
});
答案 2 :(得分:1)
您正在使用
@Html.ActionLink("India", "EmployeeBasedCountry", "Home", new {@class = "ActionLinkId", @CountryId = "1" }
用于加载页面...只需使用class或id参数来调用ajax。