MVC5中Ajax操作链接代替Html操作链接
我在我的页面上有许多select查询,并且基于它们的一些操作链接用于获取另一个数据选项卡 当我们看到用户的配置文件时,堆栈溢出的示例 摘要问题答案标签徽章等 如果用户单击选项卡中的任何一个,它会点击整个操作,页面的所有其他部分都会点击数据库,这会增加页面的加载时间。为了提高性能,我考虑应用ajax,因此在搜索之后,我得到了这个示例 局部视图MVC5中Ajax操作链接代替Html操作链接,ajax,asp.net-mvc-4,Ajax,Asp.net Mvc 4,我在我的页面上有许多select查询,并且基于它们的一些操作链接用于获取另一个数据选项卡 当我们看到用户的配置文件时,堆栈溢出的示例 摘要问题答案标签徽章等 如果用户单击选项卡中的任何一个,它会点击整个操作,页面的所有其他部分都会点击数据库,这会增加页面的加载时间。为了提高性能,我考虑应用ajax,因此在搜索之后,我得到了这个示例 局部视图 @model IEnumerable<AJAX.Models.tblStudent> <table> @foreach (var i
@model IEnumerable<AJAX.Models.tblStudent>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
<h2>Time is @DateTime.Now</h2>
索引视图
@{
ViewBag.Title = "Home Page";
}
@Ajax.ActionLink("Age 20", "Twenty", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
@Ajax.ActionLink("Age 25", "TwentyFive", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="StudentList"></div>
<h2>Time is @DateTime.Now</h2>
@section scripts{
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
@{
ViewBag.Title=“主页”;
}
@ActionLink(“20岁”,“20岁”,新的AjaxOptions
{
UpdateTargetId=“StudentList”,
InsertionMode=InsertionMode.Replace,
HttpMethod=“获取”
})
@ActionLink(“25岁”,“25岁”,新的AjaxOptions
{
UpdateTargetId=“StudentList”,
InsertionMode=InsertionMode.Replace,
HttpMethod=“获取”
})
时间是@DateTime.Now
@节脚本{
@Scripts.Render(“~/Scripts/jquery.unobtrusiveajax.min.js”)
}
这可以很好地工作,并添加了日期时间来交叉检查单击的页面是否命中数据库,从而离开页面的其他部分。想知道在MVC中使用Ajax是否正确。还有Ajax.ActionLink
注意:这取决于您的应用情况。你可以看到我刚刚找到的这篇文章 您需要编写的代码量(较少使用Ajax.ActionLink)和所需的控制级别(更多使用Html.ActionLink和jquery Ajax调用) 收集。请参阅此链接
你做的很好。但是,为什么要按年龄使用不同的过滤方法呢?它应该是一个带有参数
int Age
的方法,您将该参数作为查询字符串值的路由值传递。我同意,感谢您指出它。感谢链接,第一个来自我发布的同一作者。
@{
ViewBag.Title = "Home Page";
}
@Ajax.ActionLink("Age 20", "Twenty", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
@Ajax.ActionLink("Age 25", "TwentyFive", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="StudentList"></div>
<h2>Time is @DateTime.Now</h2>
@section scripts{
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
So it's amount of code vs level of control and functionality needed => up to you to decide which one you need.
Both approaches are perfectly fine. The Ajax.ActionLink uses the jquery.unobtrisuve-ajax script to AJAXify the anchor behind the scenes.
Personally I always use Html.ActionLink + jQuery.