《ASP.NET MVC 4 實戰》學習筆記 7:Ajax(上)

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

一、jQuery的Ajax:

1.使用jQuery形成Ajax請求:

1)建立AjaxExamples項目,添加CustomAjax控制器:

namespace AjaxExamples.Controllers{    public class CustomAjaxController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult PrivacyPolicy()        {            return PartialView();        }    }}

 2)添加自訂jQuery代碼:

$(document).ready(function () {    $(‘#privacyLink‘).click(function (event) {        event.preventDefault();        var url = $(this).attr(‘href‘);        $(‘#privacy‘).load(url);    });});

3)添加PrivacyPolicy部分視圖:

<h2>保密策略</h2>要保密哦~~

4)添加Index視圖:

@Html.ActionLink("顯示保密策略", "PrivacyPolicy", null, new {id="privacyLink"})<div id="privacy"></div><script type="text/javascript"        src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>   @*預設layout視圖已經引入jQuery但是,運行報錯,故再次引入*@<script type="text/javascript"        src="@Url.Content("~/Scripts/AjaxDemo.js")"></script>

如果使用者禁用了javascript上述頁面將會轉向PrivacyPolicy頁面,但是由於PrivacyPolicy動作返回的是部分視圖所以很不美觀,要解決此問題可以修改PrivacyPolicy動作:

public ActionResult PrivacyPolicy()        {            if (Request.IsAjaxRequest())//檢查是否Ajax調用            {                return PartialView();            }            return View();        }

2.使用Ajax提交表單資料:

1)引入AddComment動作:

namespace AjaxExamples.Controllers{    public class CustomAjaxController : Controller    {        private static List<string> _comments = new List<string>();//儲存評論列表        public ActionResult Index()        {            return View(_comments);        }        public ActionResult PrivacyPolicy()        {            if (Request.IsAjaxRequest())//檢查是否Ajax調用            {                return PartialView();            }            return View();        }        [HttpPost]        public ActionResult AddComment(string comment)        {            _comments.Add(comment);//儲存新評論            if (Request.IsAjaxRequest())            {                ViewBag.Comment = comment;                return PartialView();//將評論發送給視圖            }            return RedirectToAction("Index");        }    }}

2)添加AddComment部分視圖:

<li>@ViewBag.Comment</li>

3)修改Index視圖:

@model IEnumerable<string><ul id="comments">    @foreach (var comment in Model)    {        <li>@comment</li>    }</ul>@using (Html.BeginForm("AddComment", "CustomAjax", FormMethod.Post, new { id = "commentForm" })){    @Html.TextArea("Comment", new { rows = 5, cols = 50 })    <br />    <input type="submit" value="添加評論" />}<script type="text/javascript"        src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>   @*預設layout視圖已經引入jQuery但是,運行報錯,故再次引入*@<script type="text/javascript"        src="@Url.Content("~/Scripts/AjaxDemo.js")"></script>

4)修改AjaxDemo.js:

$(document).ready(function () {    $(‘#commentForm‘).submit(function (event) {        event.preventDefault();        var data = $(this).serialize();//將表單序列化成字串        var url = $(this).attr(‘action‘);        $.post(url, data, function (response) {            $(‘#comments‘).append(response);//將結果追加到評論列表        });    });});

 二、ASP.NET MVC的Ajax輔助器:

1.Ajax.ActionLink:

1)為項目添加jquery.unobtrusive-ajax.js:在程式管理組件管理器控制台輸入Install-Package Microsoft.jQuery.Unobtrusive.Ajax –version 3.0.0

2)修改Index視圖:

@Ajax.ActionLink("顯示保密策略", "PrivacyPolicy", new AjaxOptions{InsertionMode = InsertionMode.Replace, UpdateTargetId = "privacy"})<div id="privacy"></div><script type="text/javascript"        src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>   @*預設layout視圖已經引入jQuery但是,運行報錯,故再次引入*@<script type="text/javascript"        src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>

 啟動調試查看頁面中產生的HTML如下:

<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#privacy" href="/CustomAjax/PrivacyPolicy">顯示保密策略</a>

data-ajax標籤屬性用來指示超連結非同步執行,data-ajax-mode和data-ajax-update對應AjaxOptions對象。

當頁面載入時jquery.unobtrusive-ajax中的指令碼將找出所有帶有data-ajax標籤屬性的連結,並附加一個點擊事件。同樣,如果瀏覽器禁用javascript該連結所表現的功能如同一個常規的超連結。

2.Ajax.BeginForm:

修改Index視圖:

<ul id="comments"></ul>@using (Ajax.BeginForm("AddComment", new AjaxOptions { UpdateTargetId = "comments", InsertionMode = InsertionMode.InsertAfter })){    @Html.TextArea("Comment",new {rows=5,cols=50})    <br />    <input type="submit" value="添加評論" />}<script type="text/javascript"        src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>   @*預設layout視圖已經引入jQuery但是,運行報錯,故再次引入*@<script type="text/javascript"        src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>

3.Ajax選項:

4.與ASP.NET MVC早期版本的差別:

雖然自第一版本起Ajax輔助器已經是ASP.NET MVC的組件了,但現在jQuery是預設的。在以前版本的架構中這些輔助器總是使用微軟的Ajax庫並且未以漸進式方式產生javascript。你可以在web.config檔案的AppSettings部分將UnobtrusiveJavaScriptEnabled設定為false便會恢複到以前的行為。

現在如果調用Ajax.ActionLink會產生以下標記:

<a href="/CustomAjax/PrivacyPolicy" onclick="Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: ‘privacy‘ });">顯示保密策略</a>

它並未使用data-ajax標籤屬性,而是所有中繼資料均被放在onclick事件中。這也要求你引用MicrosoftAjax.js和MicrosoftMvcAjax.js指令碼才能使其正常工作。由於在元素的onclick標籤屬性中直接包含了方法調用,這也打斷了漸進式javascript原則。

如果你正在對ASP.NET MVC 早期版本的網站進行升級,為了保持向後相容性你可能需要這種行為。但是在所有其他情況下,最好將UnobtrusiveJavaScriptEnabled設定為ture,因為它會形成更整潔的標記並且這也是微軟未來的發展方向。

《ASP.NET MVC 4 實戰》學習筆記 7:Ajax(上)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.