MVC – 14.ajax異步請求


14.1.配置文件

14.2.AjaxHelper – 異步鏈接按鈕

14.3.AjaxHelper – 異步表單

  • AjaxOptions常見屬性:

14.4.AjaxOptions對象生成【對應】觸發ajax請求的標簽的 屬性

 

 

 

image

 

14.1.配置文件

image

頁面添加非入侵js文件

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

可在單個視圖頁面(View)上關閉

@{Html.EnableUnobtrusiveJavaScript(false);}

@{Html.EnableClientValidation(false);}

 

14.2.AjaxHelper – 異步鏈接按鈕

必須開啟 非入侵式 Ajax:導入Jquery和unobtrusiveAjax文件

View中:@Ajax.ActionLink 創建 ajax 超鏈接按鈕

一般用來請求動態生成的部分html代碼(分部視圖)

 

@Ajax.ActionLink("鏈接文本", "PartialView", new AjaxOptions() {
UpdateTargetId="divMsg",//數據顯示的html容器id
InsertionMode= InsertionMode.Replace, //替換容器內容
HttpMethod="Post" })

Controller中

public PartialViewResult PartialView()
        {
            Models.Student stu = new Models.Student() {  StudentID = 1,  Name = "Ruiky" };
            return PartialView(stu);
        }
 
PartialView.cshtml (分布視圖)
<h2>PartialView</h2>
@model _06MVCAjax_CodeFirst.Models.Student

@Html.ValueFor(s => s.StudentID)
@Html.ValueFor(s => s.Name)
 
效果圖:
2
 
 
 
 

14.3.AjaxHelper – 異步表單

1

AjaxBeginForm.cshtml

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AjaxBeginForm</title>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        function suc(resText) {
            alert(resText);
        };
        function err(xhr) {
            alert(xhr.readyState)
        }
    </script>
    <style type="text/css">
        #imgLoad{
            display:none
        }
    </style>
</head>
<body>
    <h1>異步表單:</h1>
    @using (Ajax.BeginForm("GetDateTime", "Html", new AjaxOptions()
    {
        HttpMethod = "post", //傳輸方式
        OnSuccess = "suc", //加載成功調用的js方法
        OnFailure="err", //出錯調用的js方法
        LoadingElementId = "imgLoad" //請求所現實的元素
    }))
    {
        <input type="text" name="txtName" />
        <input type="submit" />
        <div id="imgLoad">loding....</div>
    }
</body>
</html>

HtmlController.cs

public ActionResult GetDateTime()
        {
            //例:報錯的情況(除以0)
            //System.Threading.Thread.Sleep(2000);
            //int a = 0;
            //int b = 1 / a;
            string str =Request.Form["txtName"];
            System.Threading.Thread.Sleep(2000);
            return Content(DateTime.Now + "," + str);
        }

 

AjaxOptions常見屬性:

UpdateTargetId 目標元素id,獲取服務器響應后,將獲取的響應報文體顯示到目標元素innerHTML中。
InsertionMode
  • InsertAfter插入目標元素原有內容之后;

  • InsertBefore插入目標元素原有內容之前;

  • Replace 替換目標元素原有內容

LoadingElementId

LoadingElementId:異步對象readyState==4之前顯示"正在加載"狀態的元素id

 

14.4.AjaxOptions對象生成【對應】觸發ajax請求的標簽的 屬性

 

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM