天天看點

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中還有其他可以指定的屬性:

MVC 使用Helpers實作Ajax

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 on 2011-12-30 03:11 getpro 閱讀( ...) 評論( ...) 編輯 收藏

轉載于:https://www.cnblogs.com/getpro/archive/2011/12/30/2306885.html

繼續閱讀