当前位置: 代码迷 >> ASP >> Asp MVC(AJAX调用示范)
  详细解决方案

Asp MVC(AJAX调用示范)

热度:330   发布时间:2012-12-24 10:43:13.0
Asp MVC(AJAX调用示例)

Jquery定义为ASP.NET MVC 的默认JS模板。

使用AJAX的条件

1.每个AJAX请求都会制定确定的ACTION

2.Action会判定是否来自AJAX

3.针对AJAX请求必须返回一个特殊的VIEW

?

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

定义CommentController,代码如下:

view plaincopy to clipboardprint?
  1. public?class?CommentController?:?Controller ??
  2. { ??
  3. ????private?IList<STRING>?_comments?=?new?List<STRING>(); ??
  4. ??
  5. ????public?ActionResult?Index() ??
  6. ????{ ??
  7. ????????return?View(); ??
  8. ????} ??
  9. ??
  10. ????public?void?AddCommentServer() ??
  11. ????{ ??
  12. ?????????string?comment?=?Request["comment"].ToUpper(); ??
  13. ????????_comments.Add(" ??
  14. <LI>"?+?comment?+?"??
  15. ??
  16. "); ??
  17. ????????Response.ContentType?=?"text/html"; ??
  18. ????????Response.Write(string.Join("\n",?_comments.ToArray())); ??
  19. ????} ??
  20. } ??
  21. </LI>??

public class CommentController : Controller { private IList _comments = new List(); public ActionResult Index() { return View(); } public void AddCommentServer() { string comment = Request["comment"].ToUpper(); _comments.Add("


  • " + comment + " "); Response.ContentType = "text/html"; Response.Write(string.Join("\n", _comments.ToArray())); } }
  • 在Asp.net MVC中添加一个custom_ajax.js,加入下面使用ajax的脚本代码,调用AddCommentServer方法。

    view plaincopy to clipboardprint?
    1. function?getXmlHttpRequest()?{ ??
    2. ??????var?xhr; ??
    3. ??????//check?for?IE?implementation(s) ??
    4. ??????if?(typeof?ActiveXObject?!=?'undefined')?{ ??
    5. ??????????try?{ ??
    6. ??????????????xhr?=?new?ActiveXObject("Msxml2.XMLHTTP"); ??
    7. ??????????}?catch?(e)?{ ??
    8. ??????????????xhr?=?new?ActiveXObject("Microsoft.XMLHTTP"); ??
    9. ??????????} ??
    10. ??????}?else?if?(XMLHttpRequest)?{ ??
    11. ??????????//this?works?for?Firefox,?Safari,?Opera ??
    12. ??????????xhr?=?new?XMLHttpRequest(); ??
    13. ??????}?else?{ ??
    14. ??????????alert("对不起,你的浏览器不支持ajax"); ??
    15. ??????} ??
    16. ??
    17. ??????return?xhr; ??
    18. ??} ??
    19. ??
    20. ??function?getMessage()?{ ??
    21. ??????//get?our?xml?http?request?object ??
    22. ??????var?xhr?=?getXmlHttpRequest(); ??
    23. ??
    24. ??????//prepare?the?request ??
    25. ??????xhr.open("GET",?"Comment/AddCommentServer?comment="?+?document.getElementById("Comment").value,?true) ??
    26. ??
    27. ??????//setup?the?callback?function ??
    28. ??????xhr.onreadystatechange?=?function()?{ ??
    29. ??????????//readyState?4?means?we're?done ??
    30. ??????????if(xhr.readyState?!=?4)?return; ??
    31. ??
    32. ??????????//populate?the?page?with?the?result ??
    33. ??????????document.getElementById('comments').innerHTML?=?document.getElementById('comments').innerHTML?+?xhr.responseText; ??
    34. ??????}; ??
    35. ??
    36. ??????//fire?our?request ??
    37. ??????xhr.send(null); ??
    38. ??}??

    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中引入此脚本,创建一个简单的表单,并添加触发的代码:

    1. <ASP:CONTENT?id=Content2?runat="server"?ContentPlaceHolderID="MainContent">??
    2. <H4>Comments</H4>??
    3. <UL?id=comments>??
    4. ????</UL>??
    5. ??
    6. ????????<%=?Html.TextArea("Comment",?new{rows=5,?cols=50})?%>??
    7. ????????<BUTTON?onclick=getMessage()?type=submit>Add?Comment</BUTTON>??
    8. ?????????????<SPAN?id=indicator?style="DISPLAY:?none"><IMG?alt=loading...?src="../../content/load.gif"></SPAN>????????????????????????????????? ??
    9. ??
    10. </ASP:CONTENT>??
    11. ??
    12. <ASP:CONTENT?id=Content3?runat="server"?ContentPlaceHolderID="headContent">??
    13. ????<SCRIPT?src="../../Scripts/custom_ajax.js"?type=text/javascript></SCRIPT>??
    14. </ASP:CONTENT>??
    15. 第二种方式:利用Jquery


      在控制器中添加代码IndexJquery方法和AddComment方法的代码,CommentController代码如下所示:

      view plaincopy to clipboardprint?
      1. public?class?CommentController?:?Controller ??
      2. { ??
      3. ????private?IList<STRING>?_comments?=?new?List<STRING>(); ??
      4. ??
      5. ????public?ActionResult?Index() ??
      6. ????{ ??
      7. ????????return?View(); ??
      8. ????} ??
      9. ??
      10. ????public?ActionResult?IndexJquery() ??
      11. ????{ ??
      12. ????????return?View(); ??
      13. ????} ??
      14. ??
      15. ????public?ActionResult?AddComment(string?comment) ??
      16. ????{ ??
      17. ????????_comments.Add(" ??
      18. <LI>"?+?comment?+?"??
      19. ??
      20. "); ??
      21. ????????return?Content(string.Join("\n",?_comments.ToArray())); ??
      22. ????} ??
      23. ??
      24. ????public?void?AddCommentServer() ??
      25. ????{ ??
      26. ??
      27. ????????string?comment?=?Request["comment"].ToUpper(); ??
      28. ??
      29. ????????_comments.Add(" ??
      30. <LI>"?+?comment?+?"??
      31. ??
      32. "); ??
      33. ??
      34. ????????Response.ContentType?=?"text/html"; ??
      35. ????????Response.Write(string.Join("\n",?_comments.ToArray())); ??
      36. ????} ??
      37. ??
      38. } ??
      39. </LI>??
      public class CommentController : Controller { private IList _comments = new List(); public ActionResult Index() { return View(); } public ActionResult IndexJquery() { return View(); } public ActionResult AddComment(string comment) { _comments.Add("
      
      
      1. <H4>Comments</H4>??
      2. <UL?id=comments>??
      3. ????</UL>??
      4. ??
      5. ????<%?using?(Html.BeginForm("AddComment","Comment",FormMethod.Post,new?{@class="hijax"}))?{?%>??
      6. ????????<%=?Html.TextArea("Comment",?new{rows=5,?cols=50})?%>??
      7. ????????<BUTTON?type=submit>Add?Comment</BUTTON>??
      8. ?????????????<SPAN?id=indicator?style="DISPLAY:?none"><IMG?alt=loading...?src="http://www.cnblogs.com/content/load.gif"></SPAN>??
      9. ????<%?}?%>??
      10. 在View中引用Jquery: <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    16. ?
    17. " + comment + " "); return Content(string.Join("\n", _comments.ToArray())); } public void AddCommentServer() { string comment = Request["comment"].ToUpper(); _comments.Add("
    18. " + comment + " "); Response.ContentType = "text/html"; Response.Write(string.Join("\n", _comments.ToArray())); } }
    19. 根据IndexJquery,创建View表单IndexJquery.aspx:

    ?

    ?

    ?

    ?

    ?

    ?

    第三中方式,使用Ajax help

    ?<hr/>
    ???? <%using (Ajax.BeginForm("HelloAjax", new AjaxOptions { UpdateTargetId="result"}))
    ?????? {%>
    ??????? <%:Html.TextBox("query", null, new {size=40 })%>
    ??????? <input type="submit"/>
    ?????? <%} %>
    ?????? <div id="result"></div>
    ?????? <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    ??????? <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

    必须要引用这两个JS文件。新建一个ajax.BeginForm

    ?

    然后在控制器写ACTION

    ?public ActionResult HelloAjax()
    ??????? {
    ??????????? if (Request.IsAjaxRequest())
    ??????????? {
    ??????????????? return Content("Hello tuping");
    ??????????? }
    ??????????? else
    ??????????? {
    ??????????????? return null;
    ??????????? }
    ??????????
    ??????? }

    Request.IsAjaxRequest()方法可以判断HTTP请求是否是AJAX请求。?????

    查看页面即可。

    ?

    如果你返回的仅仅是一个字符串可以返回 return Content("Hello tuping");
    但是你如果返回的是一段

      相关解决方案