• Asp.net MVC2中使用Ajax的三种方式


        在Asp.net MVC中,我们能非常方便的使用Ajax。这篇文章将介绍三种Ajax使用的方式,分别为原始的Ajax调用、Jquery、Ajax Helper。分别采用这三种方式结合asp.net mvc去实现一个史上最简单的留言板。

        首先看一下原始的Ajax的调用的

         定义CommentController,代码如下:

    public class CommentController : Controller
    {
        private IList<string> _comments = new List<string>();
    
        public ActionResult Index()
        {
            return View();
        }
    
        public void AddCommentServer()
        {
     string comment = Request["comment"].ToUpper();
            _comments.Add("<li>" + comment + "</li>");
            Response.ContentType = "text/html";
            Response.Write(string.Join("\n", _comments.ToArray()));
        }
    
    }
    

        在Asp.net MVC中添加一个custom_ajax.js,加入下面使用ajax的脚本代码,调用AddCommentServer方法。

    function getXmlHttpRequest() {
          var xhr;
          //check for IE implementation(s)
          if (typeof ActiveXObject != 'undefined') {
              try {
                  xhr = new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
                  xhr = new ActiveXObject("Microsoft.XMLHTTP");
              }
          } else if (XMLHttpRequest) {
              //this works for Firefox, Safari, Opera    
              xhr = new XMLHttpRequest();
          } else {
              alert("对不起,你的浏览器不支持ajax");
          }
    
          return xhr;
      }
        
      function getMessage() {
          //get our xml http request object
          var xhr = getXmlHttpRequest();
      
          //prepare the request
          xhr.open("GET", "Comment/AddCommentServer?comment=" + document.getElementById("Comment").value, true)
          
          //setup the callback function
          xhr.onreadystatechange = function() {
              //readyState 4 means we're done
              if(xhr.readyState != 4) return;
                  
              //populate the page with the result
              document.getElementById('comments').innerHTML = document.getElementById('comments').innerHTML + xhr.responseText;
          };
      
          //fire our request
          xhr.send(null);
      }
    

        在View中引入此脚本,创建一个简单的表单,并添加触发的代码:

    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <h4>Comments</h4>    
        <ul id="comments">        
        </ul>
            <%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
            <button type="submit" onclick="getMessage()">Add Comment</button>
                 <span id="indicator" style="display:none"><img src="http://www.cnblogs.com/content/load.gif" alt="loading..." /></span>                                 
    
    </asp:Content>
    
    <asp:Content ID="Content3" ContentPlaceHolderID="headContent" runat="server">
        <script src="http://www.cnblogs.com/Scripts/custom_ajax.js" type="text/javascript"></script>
    </asp:Content>
    
       效果如下:
    3 
     
     
    第二种方式:利用Jquery:
        在控制器中添加代码IndexJquery方法和AddComment方法的代码,CommentController代码如下所示
    public class CommentController : Controller
    {
        private IList<string> _comments = new List<string>();
    
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult IndexJquery()
        {
            return View();
        }
    
        public ActionResult AddComment(string comment)
        {
            _comments.Add("<li>" + comment + "</li>");
            return Content(string.Join("\n", _comments.ToArray()));
        }
    
        public void AddCommentServer()
        {
    string comment = Request["comment"].ToUpper();
    
            _comments.Add("<li>" + comment + "</li>");
    
            Response.ContentType = "text/html";
            Response.Write(string.Join("\n", _comments.ToArray()));
        }
    
    }
    
        根据IndexJquery,创建View表单IndexJquery.aspx:
        <h4>Comments</h4>    
        <ul id="comments">        
        </ul>
        
        <% using (Html.BeginForm("AddComment","Comment",FormMethod.Post,new {@class="hijax"})) { %>    
            <%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
            <button type="submit">Add Comment</button>
                 <span id="indicator" style="display:none"><img src="http://www.cnblogs.com/content/load.gif" alt="loading..." /></span>                                 
        <% } %>
    
        在View中引用Jquery:
        <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    

        添加下面脚本:

        <script type="text/javascript">
            //execute when the DOM has been loaded
            $(document).ready(function () {
                //wire up to the form submit event
                $("form.hijax").submit(function (event) {
                    event.preventDefault();  //prevent the actual form post
                    hijack(this, update_sessions, "html");
                });
            });
    
            function hijack(form, callback, format) {
                $("#indicator").show();
                $.ajax({
                    url: form.action,
                    type: form.method,
                    dataType: format,
                    data: $(form).serialize(),
                    completed: $("#indicator").hide(),
                    success: callback
                });
            }
    
            function update_sessions(result) {
                //clear the form
                $("form.hijax")[0].reset();
                $("#comments").append(result);
            }
        
        </script>
    

     

     
     
     
     
     
     
     
     效果:与方式一效果一样
     
    第三种方式:Ajax Helper。
    
    
        将最简单的留言板修改成Ajax Helper的方式。

        1、首先了解一下Ajax Helper下面四种方法。

            a、Ajax.ActionLink():它将渲染成一个超链接的标签,类似于Html.ActionLink()。当它被点击之后,将获取新的内容并将它插入到HTML页面中。

            b、Ajax.BeginForm():它将渲染成一个HTML的Form表单,类似于Html.BeginForm()。当它提交之后,将获取新的内容并将它插入到HTML页面中。

            c、Ajax.RouteLink():Ajax.RouteLink()类似于Ajax.ActionLink()。不过它可以根据任意的routing参数生成URL,不必包含调用的action。使用最多的场景是自定义的IController,里面没有action。

            d、Ajax.BeginRouteForm():同样Ajax.BeginRouteForm()类似于Ajax.BeginForm()。这个Ajax等同于Html.RouteLink()。

        这个例子中使用Ajax.BeginForm(),下面具体了解Ajax.BeginForm()的参数。看下面代码

        <% using (Ajax.BeginForm("AddComment", new AjaxOptions
                                                {
                                                    HttpMethod = "POST", 
                                                    UpdateTargetId = "comments",
                                                    InsertionMode = InsertionMode.InsertAfter                                                
                                                })) { %>
    

        actionName:AddComment(action的名字)

        controllerName:CommentController(Controller的名字)

        ajaxOptions:

             HttpMethod:Ajax的请求方式,这里为POST

             UpdateTargetId :Ajax请求的结果显示的标签的ID,这里为comments

             InsertionMode:将Ajax结果插入页面的方式,这里将ajax的结果放置到comments的后面

    2、实现:

        在CommentController中添加IndexAjaxHelp方法。

    public ActionResult IndexAjaxHelp()
    {
        return View();
    }
    

        根据IndexAjaxHelp生成View表单IndexAjaxHelp.aspx,定义表单:

        <h4>Comments</h4>    
        <ul id="comments">        
        </ul>
        
        <% using (Ajax.BeginForm("AddComment", new AjaxOptions
                                                {
                                                    HttpMethod = "POST", 
                                                    UpdateTargetId = "comments",
                                                    InsertionMode = InsertionMode.InsertAfter                                                
                                                })) { %>
        
            <%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
            <button type="submit">Add Comment</button>
                                                
        <% } %>
    

        要在此View中添加下面两个脚本文件:

        <script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
        <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    
    
    

       这样就行了,我们发现比用Jquery方便很多,但是使用Jquery将灵活很多。

      3、效果:和方式一样。

    总结:本文非常的简单,在asp.net mvc中实现了3中ajax的调用方式,实现了一个最简单的留言板程序。推荐使用Jquery和Ajax Helper这两种。Ajax Helper使用非常简单,Jquery比较灵活。

    更新:三种方式都实现了一个最简单的留言板程序

    参考:

        ASP.NET MVC 2 In Action

        Pro ASP.NET MVC 2 Framework, Second Edition

    代码:https://files.cnblogs.com/zhuqil/AjaxDemo.rar



    (全文完)


    以下为广告部分

    您部署的HTTPS网站安全吗?

    如果您想看下您的网站HTTPS部署的是否安全,花1分钟时间来 myssl.com 检测以下吧。让您的HTTPS网站变得更安全!

    SSL检测评估

    快速了解HTTPS网站安全情况。

    安全评级(A+、A、A-...)、行业合规检测、证书信息查看、证书链信息以及补完、服务器套件信息、证书兼容性检测等。

    SSL证书工具

    安装部署SSL证书变得更方便。

    SSL证书内容查看、SSL证书格式转换、CSR在线生成、SSL私钥加解密、CAA检测等。

    SSL漏洞检测

    让服务器远离SSL证书漏洞侵扰

    TLS ROBOT漏洞检测、心血漏洞检测、FREAK Attack漏洞检测、SSL Poodle漏洞检测、CCS注入漏洞检测。

  • 相关阅读:
    Spring Bean(一)
    Spring IOC(一)
    三种常用的查找算法
    分布式架构的一致性
    Java内存区域笔记(一)
    分组交换和电路交换
    Python说文解字_Python之多任务_03
    Python说文解字_Python之多任务_02
    Python说文解字_Python之多任务_01
    Python说文解字_杂谈09
  • 原文地址:https://www.cnblogs.com/zhuqil/p/1780285.html
Copyright © 2020-2023  润新知