MVC中的Ajax(AjaxHelper)

authour: chenboyi
updatetime: 2015-04-30 20:47:49
friendly link:  

 

 

 

 


 

目录

  1,思维导图

  2,ActionLink()

  3,BeginForm()

  4, Ajax非侵入式脚本

 


 ps:mvc中同样也能用jquery中的方法来发起ajax请求

1,思维导图:

 

 2,ActionLink():

  2.1 示例说明:

  下面是获取服务器的时间的小例子,主要有两个文件:1,getDate.cshtml ;2,getDateController(action:GetTime)

  2.2 CodeSimple:

  1 //getDate.cshtml
  2 @{
  3     Layout = null;
  4 }
  5 
  6 <!DOCTYPE html>
  7 
  8 <html>
  9 <head>
 10     <meta name="viewport" content="width=device-width" />
 11     <title>Index</title>
 12     <style>
 13         .none {
 14             display: none;
 15         }
 16         #dispTime {
 17             border:1px solid red;
 18             height:50px;
 19         }
 20     </style>
 21     <script src="~/Scripts/jquery-1.7.1.js"></script>
 22     <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
 23 
 24     <script type="text/javascript">
 25         //表示开始请求
 26         function begin() {
 27             //alert("begin()");
 28             $("#loading1").removeClass("none");
 29         }
 30 
 31         //表示成功 如果后台action利用的是 return Json()方法返回,此处的obj就是被Json.parse()自动转换的一个js对象(数组)
 32         function sucess1(obj) {
 33             var o = obj;  //{now:2014-2-23 10:09:09}
 34             //开始利用obj 执行当前的业务逻辑
 35             //alert("sucess1():" + o.now);
 36         }
 37 
 38         //表示失败
 39         function fail(obj) {
 40            // alert("fail():" + obj);
 41         }
 42 
 43         //表示完成
 44         function comp(obj) {
 45             var o = obj;
 46            // alert("comp():" + o)
 47             $("#loading1").addClass("none");
 48         }
 49 
 50     </script>
 51 </head>
 52 <body>
 53     <div>
 54         @*<a href="/AjaxHelper/GetTime" data-ajax="true" data-ajax-url="/AjaxHelper/GetTime"></a>*@
 55         @Ajax.ActionLink(
 56         "Get请求服务器时间"
 57         , "GetTime"
 58         , "AjaxHelper"
 59         , new AjaxOptions()
 60        {
 61            Confirm = "是否要请求服务器吗?",
 62            HttpMethod = "Get",
 63            InsertionMode = InsertionMode.Replace,  //Replace:表示最新的结果替换原来的结果          
 64            Url = Url.Action("GetTime", "AjaxHelper"),  //负责将结果生成 到a标签的 data-ajax-url属性中
 65            LoadingElementId = "loading",  // 当请求发出时显示id=loading 元素,提醒用户当前正在处理
 66            OnSuccess = "sucess1",  //表示服务器响应回来以后调用的成功回调函数
 67            OnComplete = "comp", //表示服务器已经响应完成,并且执行了OnSuccess,是在OnSuccess调用之后被触发
 68            OnBegin = "begin",  //发出ajax请求的时候被触发
 69            OnFailure = "fail" //当ajax请求失败的回调函数
 70        })
 71     </div>
 72     <div>
 73          @Ajax.ActionLink(
 74         "Get请求服务器时间1"
 75         , "GetTime1"
 76         , "AjaxHelper"
 77         , new AjaxOptions()
 78        {
 79            Confirm = "是否要请求服务器吗?",
 80            HttpMethod = "Get",
 81            InsertionMode = InsertionMode.Replace,  //Replace:表示最新的结果替换原来的结果 
 82            UpdateTargetId = "dispTime", //将服务器响应回来的结果填充到 id = dispTime 的元素中,注意action方法中只能返回文本字符串,不能返回json格式的字符串
 83            Url = Url.Action("GetTime1", "AjaxHelper"),  //负责将结果生成 到a标签的 data-ajax-url属性中
 84            LoadingElementId = "loading" // 当请求发出时显示id=loading 元素,提醒用户当前正在处理          
 85        })
 86     </div>
 87 
 88     <div>
 89           @Ajax.ActionLink(
 90         "Post请求服务器时间"
 91         , "GetTime2"
 92         , "AjaxHelper"
 93         , new AjaxOptions()
 94        {
 95            Confirm = "是否要请求服务器吗?",
 96            HttpMethod = "Post",
 97            InsertionMode = InsertionMode.Replace,  //Replace:表示最新的结果替换原来的结果 
 98            UpdateTargetId = "dispTime", //将服务器响应回来的结果填充到 id = dispTime 的元素中,注意action方法中只能返回文本字符串,不能返回json格式的字符串
 99            Url = Url.Action("GetTime2", "AjaxHelper"),  //负责将结果生成 到a标签的 data-ajax-url属性中
100            LoadingElementId = "loading" // 当请求发出时显示id=loading 元素,提醒用户当前正在处理          
101        })
102     </div>
103     <div id="dispTime"></div>
104     <div id="loading" style="color: red; display: none">正在加载中.....</div>
105     <div id="loading1" style="color: red;" class="none">正在加载中1111111.....</div>
106 </body>
107 </html>

 

 1         /// <summary>
 2         /// 被ajax请求的方法
 3         /// </summary>
 4         /// <returns></returns>
 5         public ActionResult GetTime()
 6         {
 7             System.Threading.Thread.Sleep(2000);
 8             //格式:{"time":"2014-8-4 12:00:00"}
 9             return Json(new { time = DateTime.Now.ToString() }, JsonRequestBehavior.AllowGet);
10         }
11 
12  //public ActionResult GetTime1()
13         //{
14         //    System.Threading.Thread.Sleep(2000);
15 
16         //    return Content(DateTime.Now.ToString());
17         //}

 

3,BeginForm():

  3.1 示例说明:

  下面是通过一个简单的“模拟新增”(并非真的做新增操作)方法,说明BeginForm的使用方式。

  其中主要有两段代码:1,Add.schtml;2,C#(Add方法)

  3.2 CodeSimple:

 1 //Add.cshtml
 2 @{
 3     Layout = null;
 4 }
 5 @model Mvc03知识点.Pig
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <title>Add</title>
13     <style type="text/css">
14         #saveing {
15             position: absolute;
16             left: 400px;
17             top: 300px;
18             border: 1px solid blue;
19             width: 100px;
20         }
21 
22         .none {
23             display: none;
24         }
25     </style>
26     <script src="~/Scripts/jquery-1.7.1.js"></script>
27     <script src="~/Scripts/jquery.validate.js"></script>
28     <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
29     <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
30     <script type="text/javascript">
31         function begin() {
32             //将saveing 对于的div上的none 类移除,显示div给用户
33             $("#saveing").removeClass("none");
34         }
35 
36         function sucess1(jsobj) {
37             //1.0 接收 jsojb
38             //2.0 利用jsobj 做业务逻辑处理
39             if (jsobj.status == "sucess") {
40                 alert("新增成功");
41             } else {
42                 alert(jsobj.msg);
43             }
44             //将saveing 对于的div 隐藏
45             $("#saveing").addClass("none");
46         }
47 
48     </script>
49 </head>
50 <body>
51     <div>
52         @using (Ajax.BeginForm(
53         "Add"
54         , "ajaxBegForm"
55         , new AjaxOptions()
56         {
57             HttpMethod = "Post",
58             OnBegin = "begin",
59             OnSuccess = "sucess1",
60             Url = Url.Action("Add", "ajaxBegForm")
61         }))
62         {
63             @Html.TextBoxFor(c=>c.ID)<br />
64             @Html.TextBoxFor(c=>c.Name)  @Html.ValidationMessageFor(c=>c.Name)<br />
65             @Html.TextBoxFor(c=>c.Age)<br />
66             <input type="submit" value="新增" />
67         }
68     </div>
69     <div id="saveing" class="none">数据正在保存</div>
70 </body>
71 </html>

 

 1  #region 2.0 演示@Ajax.BeginForm()的ajax操作
 2 
 3         [HttpGet]
 4         public ActionResult Add()
 5         {
 6             return View();
 7         }
 8 
 9         [HttpPost]
10         public ActionResult Add(Pig pig)
11         {
12             //TODO:执行新增逻辑代码
13             //以json格式将提醒数据返回
14             return Json(new { status = 0, msg = "新增成功" });
15         }
16 
17         #endregion

 

 

4, Ajax非侵入式脚本
  ajax请求的步骤:
  4.1、利用@Ajax 中的相应方法生成相应html元素
  4.2、导入两个脚本:
   <script src="~/Scripts/jquery-xx.js"></script>
      <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
  4.3、确认web.config中  <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 的值为true,表示开启非侵入式脚本

  

posted on 2015-04-30 22:34  两宝程序cboii  阅读(453)  评论(0编辑  收藏  举报

导航