ASP.NET MVC 实践系列4-Ajax应用

ASP.NET MVC 实践系列4-Ajax应用

ASP.NET MVC中支持Ajax的方式和webform中有些区别,没有了updatepanel,所以对于初学者来说在最开始应用时似乎没有在webform中简单,但实际使用上更为灵活而跟webform比较并没有增加多少复杂度。

一、ASP.NET MVC Ajax 的 Helpers

对于ASP.NET MVC中的Ajax的学习,需要重点了解Ajax.ActionLink()和Ajax.BeginForm()这两个Helper,Ajax是System.Web.Mvc.ViewPage中的属性,它返回的类型是AjaxHelper,而ASP.NET MVC中的View都是继承于System.Web.Mvc.ViewPage,所以在页面上能直接使用这两个Helper。

1、Ajax.ActionLink():向客户端输入一个链接地址,跟Html.ActionLink()很相似,当单击这个链接时可以异步调用Controller中的方法

Ajax.ActionLink()方法有许多重载,我们这里举例说明其中一个比较常用的重载:

public static string ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions);
linkText:是显示在客户端的文本

actionName:是Action的名字,默认情况下我们会使用当前的Controller。

routeValues:将传入到Controller中方法的参数

ajaxOptions:配置Ajax的一些选项,看完下面的例子我们再详细讲解这个配置选项。

这里先举一个简单的例子:

View:

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>

<%=Ajax.ActionLink("test","Hello",new{name="lfm"},new AjaxOptions{UpdateTargetId="results"}) %>
<div id="results">
</div>

虽然ASP.NET MVC 的sctrpts中已经有了Ajax的脚本,但使用之前仍然还要在页面中引用。Ajax.ActionLink("test","Hello",new{name="lfm"},new AjaxOptions{UpdateTargetId="results"}) 的意思是前端页面显示的文本为test,当点击test时会调用Controller中的Hello方法,参数为lfm,返回的内容会在id=results的标签中显示。

Controller:

Code
public ActionResult ActionLinkTest()
{
return View();
}
public string Hello(string name)
{
return "Hello:" + name;
}

2、ajaxOptions重要选项讲解

属性 类型 解释
Confirm string 如果指定了这个选项,当单击链接时会弹出一个确认窗口

LoadingElementId string 如果指定了这个选项,当点击链接时,会将指定的id标签内容的css改为显示状态
UpdateTargetId string 如果指定了这个选项,异步调用完之后的返回值会替换这个标签。

Confirm例子:在View中键入 <%=Ajax.ActionLink("ConfirmTest", "Hello", new { name = "lfm" }, new AjaxOptions {Confirm="你确定么", UpdateTargetId = "results" })%>
当单击ConfirmTest时会弹出如下窗口:



LoadingElementId例子:

View:

<%=Ajax.ActionLink("LoadingTest","HelloSleep",new{name="lfm"},new AjaxOptions{LoadingElementId="loading",UpdateTargetId="results"}) %>
<div id="loading" style="display: none">
Loading......
</div>
<div id="results">
</div>

Controller:

Code
public string HelloSleep(string name)
{
Thread.Sleep(2000);
return "Hello:" + name;
}

3、Ajax.BeginForm():跟Html.BeginForm()很相似,当按提交按钮时会异步的调用相应的Controller中的方法

View:

<% using (Ajax.BeginForm("Hello",
new AjaxOptions { UpdateTargetId = "myResults" }))
{ %>
<%=Html.TextBox("name") %>
<input type="submit" value="调用" />
<% } %>
<div id="myResults">
返回结果
</div>

Controller:

public string Hello(string name)
{
return "Hello:" + name;
}
public ActionResult BeginFormTest()
{
return View();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值