技术开发 频道

Asp.net MVC简单实用三种使用Ajax方式

    【IT168 技术】  在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="../../content/load.gif" alt="loading..." /></span>                                

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="headContent" runat="server">
    
<script src="../../Scripts/custom_ajax.js" type="text/javascript"></script>
</asp:Content>

 

  效果如下:

 Asp.net mvc 2中使用Ajax的第一种方法

  第二种方式:利用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,定义表单: 
      要在此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

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

0
相关文章