The use of Ajax in ASP. NET MVC [share]

Source: Internet
Author: User
Tags form post html form actionlink

Article transferred from http://www.huiyoumi.wang/upload/forum.php?mod=viewthread&tid=75&extra=

ASP. NET MVC discards the highly encapsulated controls of ASP. WebForm, which gives us more familiarity with the underlying HTML. You can control the structure, style, and behavior of HTML more freely and flexibly. And this is really a lot better for Ajax than WebForm. I made a discussion about ASP. NET MVC more convenient to use Ajax, to share, welcome to shoot bricks. The following three ways to demonstrate the use of Ajax, both with a simple demo show you want to study more, ask questions and share experience.

First, directly write the JS code to achieve Ajax:

Because the code in the ASP is better controlled, we can make AJAX requests directly in HTML via JS, and return XML or JSON in the Controller's action to implement the Ajax effect, which is the most primitive method. Browser and many issues need to be considered, not recommended.

The reference code is as follows: JS code:

  1. var xhr;
  2. function Getxhr ()
  3. {
  4. try {
  5. Xhr=new ActiveXObject ("msxml2.xmlhttp");
  6. } catch (e) {
  7. try {
  8. Xhr=new ActiveXObject ("Microsoft.XMLHTTP");
  9. } catch (e) {
  10. Xhr=false;
  11. }
  12. }
  13. if (!xhr&&typeof xmlhttprequest!= ' undefined ')
  14. {
  15. Xhr=new XMLHttpRequest ();
  16. }
  17. return XHR;
  18. }
  19. function Openxhr (method,url,callback)
  20. {
  21. GETXHR ();
  22. Xhr.open (Method,url);
  23. Xhr.onreadystatechange=function ()
  24. {
  25. if (xhr.readystate!=4) return;
  26. Callback (XHR);
  27. }
  28. Xhr.send (NULL);
  29. }
  30. function LoadXML (method,url,callback)
  31. {
  32. GETXHR ();
  33. Xhr.open (Method,url);
  34. Xhr.setrequestheader ("Content-type", "Text/xml");
  35. Xhr.setrequestheader ("Content-type", "GBK");
  36. Xhr.onreadystatechange=function ()
  37. {
  38. if (xhr.readystate!=4) return;
  39. Callback (XHR);
  40. }
  41. Xhr.send (NULL);
  42. }
Copy Code

Background code:

    1. Public ActionResult getnews (int CategoryID)
    2. {
    3. Newscollectionmodel newscollection = new Newscollectionmodel ();
    4. ............
    5. Jsonresult Myjsonresult = new Jsonresult ();
    6. Myjsonresult = newscollection;
    7. return myjsonresult;
    8. }
Copy Code

The second type: Ajax calls with jquery:

In VS 2010, the IDE fully supports the Smart Display of jquery, the use of JQ in development to achieve the JS effect is very good, and can save a lot of energy and time. So it's also a good idea to use jquery for development in Ajax.

The approximate implementation code is as follows:

  1. <% using (Html.BeginForm ("AddComment", "Comment", formmethod.post,new {@class = "Hijax"})) {%>
  2. <%= Html.textarea ("Comment", New{rows=5, cols=50})%>
  3. <button type= "Submit" >add comment</button>
  4. <span id= "indicator" style= "Display:none" ></span>
  5. <%}%>
  6. To reference jquery in view:
  7. <script src= "Http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type= "Text/javascript" ></script>
  8. Add the following script:
  9. <script type= "Text/javascript" >
  10. Execute when the DOM has been loaded
  11. $ (document). Ready (function () {
  12. Wire up to the form submit event
  13. $ ("Form.hijax"). Submit (Function (event) {
  14. Event.preventdefault (); Prevent the actual form post
  15. Hijack (this, update_sessions, "html");
  16. });
  17. });

  18. function hijack (form, callback, format) {
  19. $ ("#indicator"). Show ();
  20. $.ajax ({
  21. Url:form.action,
  22. Type:form.method,
  23. Datatype:format,
  24. Data: $ (form). Serialize (),
  25. Completed: $ ("#indicator"). Hide (),
  26. Success:callback
  27. });
  28. }

  29. function Update_sessions (Result) {
  30. Clear the form
  31. $ ("Form.hijax") [0].reset ();
  32. $ ("#comments"). Append (result);
  33. }

  34. </script>
Copy Code

The third method: Use Microsoft's own AJAX helper framework to implement.

  1. <% using (Ajax.beginform ("AddComment", New ajaxoptions
  2. {
  3. HttpMethod = "POST",
  4. Updatetargetid = "Comments",
  5. Insertionmode = Insertionmode.insertafter
  6. })) {%>

  7. <%= Html.textarea ("Comment", New{rows=5, cols=50})%>
  8. <button type= "Submit" >add comment</button>

  9. <%}%>
Copy Code

The second and third method in the blog park has a blog, I have a direct reference, the specific address is as follows:http://www.cnblogs.com/zhuqil/archive/2010/07/18/1780285.html

It is primarily a matter of my own opinion and attention to the Ajax helper record.

First, Ajax Helper is a Microsoft-provided AJAX framework, in order to use AJAX helper must use the Microsoft provided two JS framework:

<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>

Second, Ajax Helper has several uses

Ajax.actionlink (): It renders a hyperlink tag, similar to Html.ActionLink (). When it is clicked, it gets the new content and inserts it into the HTML page.

ajax.beginform (): It renders as an HTML form form, similar to Html.BeginForm (). When it commits, it gets the new content and inserts it into the HTML page.

Ajax.routelink (): Ajax.routelink () is similar to Ajax.actionlink (). However, it can generate a URL based on any of the routing parameters, without having to include the invoked action. The most used scene is a custom icontroller with no action in it.

ajax.beginrouteform (): same ajax.beginrouteform () similar to Ajax.beginform (). This Ajax equates to Html.routelink ().

and the parameters in each method will be different, the specific usage see:http://msdn.microsoft.com/zh-cn/library/system.web.mvc.ajaxhelper_methods (v=vs.98). ASPX

One of the important parameters is: ajaxoption, there are several properties, mainly to specify the behavior of Ajax.

The use of Ajax in ASP. NET MVC [share]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.