在MVC 5中使用Ajax Action Link而不是Html Action链接

时间:2016-04-20 03:04:41

标签: ajax asp.net-mvc-4

我在我的页面上有很多选择查询,基于它们使用的几个Action链接得到了另一个数据选项卡。

当我们看到我们看到的用户的个人资料时,有关堆栈溢出的示例

摘要 问题 答案 标记 徽章等。

如果用户点击其中任何一个标签,它就会点击整个操作,页面的所有其他部分都会点击数据库,这会导致页面的加载时间增加。为了提高性能,我需要应用ajax,所以在搜索后我得到了这个例子。

部分视图。

@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>

控制器

public ActionResult Index()
{
    return View();
}

public PartialViewResult Twenty()
{
    var result = from r in db.tblStudents where r.Age == 20 select r;
    return PartialView("_Country", result);
}

public PartialViewResult TwentyFive()
{
    var result = db.tblStudents.Where(x => x.Age >= 25);
    return PartialView("_Country", result);
}

索引视图

@{
    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")
 }

这很好,并且添加了日期时间来交叉检查被点击的页面是否会访问数据库而不是页面的其他部分。想知道它是否是在MVC中使用Ajax的正确方法。和Ajax.ActionLink一样。

注意:this tutorial

1 个答案:

答案 0 :(得分:0)

取决于您的应用情况。你可以看到我发现的这篇文章。

  

在你必须编写的代码量中(使用Ajax.ActionLink减少)和你需要的控制级别(更多使用Html.ActionLink和jquery ajax调用)。

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.

collectted。请参阅此链接

link1

link2

link3

相关问题