MVC 使用Helpers实现Ajax

MVC 使用Helpers实现Ajax

View

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


<div id="TimePnl" style="width: 300px; height: 30px; border: 1px dotted silver;">
</div>
@Ajax.ActionLink("Click Me", "GetTime", new AjaxOptions { UpdateTargetId = "TimePnl" })
复制代码

MVC3需要在_Layout.cshtml 中加入

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

 

Controller

public ActionResult GetTime()
{
return Content("Now Time:"+DateTime.Now.ToString());
}

 

示例使用ActionLink超链接发送请求到GetTime,返回一个ContentResult,通过AjaxOptions中的UpdateTargetId属性指定了需要更新的页面元素。

AjaxOptions中还有其他可以指定的属性:

OnComplete和OnSuccess的区别:OnComplete是获取了Http请求时引发的,此时页面还没有进行更新,OnSuccess是在页面已经更新后引发的。

 

使用Ajax.BeginForm

View

复制代码
<div id="myPnl" style="width: 300px; height: 30px; border: 1px dotted silver;">
</div>
// @using Ajax.BeginForm("SaveAlert", new AjaxOptions { UpdateTargetId = "myPnl" }))
@using (Ajax.BeginForm("Save", new AjaxOptions { UpdateTargetId = "myPnl" }))
{
@Html.Label("I am Label")
<br />
<input id="TextBox1" value="I am TextBox" />

<input type="submit" value="提交" />
}
复制代码

Controller

复制代码
public ActionResult Save(string str)
{
return Content("Save OK!");
}

public ActionResult SaveAlert(string str)
{
return JavaScript("alert('Save Complete!')");
}
复制代码
 
posted @ 2012-10-30 16:25  祥飞翔  阅读(290)  评论(0编辑  收藏  举报