日期:2014-05-16  浏览次数:20770 次

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