Use of Ajax in Asp.net MVC, mvcajax

Source: Internet
Author: User
Tags form post actionlink

Use of Ajax in Asp.net MVC, mvcajax

Asp.net MVC abandons the highly encapsulated controls of Asp.net WebForm, so that we are more close to the underlying HTML. The structure, style, and behavior of HTML can be controlled more freely and flexibly. For Ajax, Asp.net MVC is indeed much better than WebForm. I have discussed the more convenient use of Ajax in Asp.net MVC, And I will share it with you. The following three methods are used to demonstrate the use of ajax. Both of them are used as a simple demo to show you how to study, ask questions, and share your experience.

First, directly write JS Code to implement Ajax:

Because the code on the Asp.net browser can be better controlled, we can directly send Ajax requests in HTML, and return XML or Json in the Controller action to achieve Ajax effect, this method is the most primitive method. It is not recommended to consider browsers and many problems.

The reference code is as follows: JS Code:

    var xhr;        function getXHR()        {        try {        xhr=new ActiveXObject("Msxml2.XMLHTTP");        } catch (e) {        try {        xhr=new ActiveXObject("Microsoft.XMLHTTP");        } catch (e) {        xhr=false;        }        }        if(!xhr&&typeof XMLHttpRequest!='undefined')        {        xhr=new XMLHttpRequest();        }        return xhr;        }        function openXHR(method,url,callback)        {        getXHR();        xhr.open(method,url);        xhr.onreadystatechange=function()        {        if(xhr.readyState!=4)return;        callback(xhr);        }        xhr.send(null);        }        function loadXML(method,url,callback)        {        getXHR();        xhr.open(method,url);        xhr.setRequestHeader("Content-Type","text/xml");        xhr.setRequestHeader("Content-Type","GBK");        xhr.onreadystatechange=function()        {        if(xhr.readyState!=4)return;        callback(xhr);        }        xhr.send(null);        }  

Background code:

    public ActionResult GetNews(int CategoryID)              {                  NewsCollectionModel newsCollection = new NewsCollectionModel();                  …………                  JsonResult myJsonResult = new JsonResult();                  myJsonResult = newsCollection;                  return myJsonResult;              }  

Method 2: Ajax call using Jquery:

In VS 2010, IDE fully supports the intelligent display of Jquery. In development, Jq is used to achieve excellent JS effects, saving a lot of energy and time. Therefore, using JQuery for development in Ajax is also a good method.

The approximate implementation code is as follows:

<% Using (Html. beginForm ("AddComment", "Comment", forpolichod. post, new {@ class = "hijax"}) {%> <% = Html. textArea ("Comment", new {rows = 5, cols = 50 }) %> <button type = "submit"> Add Comment </button> <span id = "indicator" style = "display: none">  </span> <% }%> reference Jquery in View: <script src =" http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js "Type =" text/javascript "> </script> Add the following 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>

Method 3: Use the Ajax Helper framework provided by Microsoft.

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

The second and third methods in the blog Park has a blog to explain, I directly cited, the specific address is as follows: http://www.cnblogs.com/zhuqil/archive/2010/07/18/1780285.html

I mainly record my views and precautions on Ajax helper.

First, Ajax Helper is an Ajax framework provided by Microsoft. To use Ajax Helper, you must use the two Js frameworks provided by Microsoft:

 

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

 

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

Ajax. BeginForm ():It renders an HTML Form, similar to Html. BeginForm (). After it is submitted, it obtains 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 routing parameter without containing the called action. The most commonly used scenario is the custom IController, with no action in it.

Ajax. BeginRouteForm ():Similarly, Ajax. BeginRouteForm () is similar to Ajax. BeginForm (). This Ajax is equivalent to Html. RouteLink ().

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

An important parameter is AjaxOption, which has the following attributes, mainly to regulate Ajax behavior.

Related Article

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.