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>

 

   效果如下:
 
 
 
第二种方式:利用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比较灵活。

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




本文转自麒麟博客园博客,原文链接:http://www.cnblogs.com/zhuqil/archive/2010/07/18/1780285.html,如需转载请自行联系原作者

相关文章
|
2月前
|
开发框架 前端开发 JavaScript
ASP.NET AJAX使用方法概述(三)
ASP.NET AJAX使用方法概述(三)
29 1
|
2月前
|
开发框架 缓存 前端开发
安装ASP.NET AJAX (一安装)
安装ASP.NET AJAX (一安装)
41 0
|
2月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
47 0
|
2月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
184 5
|
2月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
|
2月前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
|
JavaScript 前端开发
ExtJs下拉框组件Ajax方式显示
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.
848 0
|
8月前
|
XML 前端开发 JavaScript
什么是Ajax和jquery
什么是Ajax和jquery
66 0
|
2月前
|
JSON 前端开发 Java
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
85 0
|
2月前
|
敏捷开发 JavaScript 前端开发
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤

相关实验场景

更多