Ajax-assisted solution for ASP. NET MVC

Source: Internet
Author: User
Tags configuration settings actionlink

Previously, we have briefly introduced how to use Jquery in MVC, because we must understand Jquery if Ajax is used. This blog will give a general introduction to ASP. net mvc: How to Use Ajax as an auxiliary method. This blog is my reading notes. If it is not well written, ask your friends to come up and learn it together.
1. Preparations
(1) At the beginning of MVC learning, we need to introduce ASP. net mvc framework, but there are already a lot of such articles, and I personally feel very simple, so I will not introduce them here.
(2) ASP. in the. net mvc framework, we can use the HTML-assisted method to create a form and link to the Controller operation. net mvc framework also contains a set of Ajax auxiliary methods. They can also be used to create forms and connections to Controller operations, but they are asynchronous, when using these auxiliary methods, you do not need to write any script code to implement program Asynchronization.
(3) In the background, these Ajax auxiliary methods depend on Jquery extensions of non-intrusive MVC. If you use these auxiliary methods, you need to introduce the script file jquery. unobtrusive-ajax.js, as to how to reference I have already said in the previous blog, here will not post the code.
2. ActionLink method of Ajax
(1) In the Razor view, AJAX-assisted methods can be accessed through Ajax attributes, which is similar to HTML-assisted methods, most of the Ajax auxiliary methods on Ajax attributes are extension methods (except for the AjaxHelper type ).
(2) The ActionLink method of Ajax attributes can create an anchor tag with asynchronous behavior. Now we can modify it on the MVC3.0 MusicStore Project released by Microsoft. Anyone who does not have this project can add an underground group and then share it with me. Add the following code to view "Views/Home/Index. cshtml.

Copy codeThe Code is as follows:
<Div id = "dailydeal">
@ Ajax. ActionLink ("Click me", "DailyDeal", new AjaxOptions
{
UpdateTargetId = "dailydeal ",
InsertionMode = InsertionMode. Replace,
HttpMethod = "Get"
})
</Div>

(3) The first parameter of the ActionLink method specifies the connection text, and the second parameter is the name of the operation to be called asynchronously, similar to the HTML auxiliary method with the same name. The AjaxOptions parameter significantly differs from the HTML and Ajax auxiliary methods. This parameter specifies the methods used to send requests and process the results returned by the server. The parameters also include methods used to handle errors, displays loading elements, confirmation dialog box, and other options. To get the server response, you need to add a DailyDeal operation on the Controller HomeController. The Code is as follows:

Copy codeThe Code is as follows:
Public ActionResult DailyDeal ()
{
Var album = GetDailyDeal ();
Return PartialView ("_ DailyDeal", album );
}
Private Album GetDailyDeal ()
{
Return storeDB. Albums. OrderBy (a => a. Price). First ();
}

(4) the return value of the target operation connected by the Ajax operation is plain text or HTML. The following Razor code is in the _ DailyDeal. cshtml file in the Views/Home folder of the project.

Note: The content generated by Ajax. ActionLink can obtain the server response and directly port the new content to the page. Why? Next we will introduce the working principle of Asynchronous Operation connections.
3. HTML5 features
(1) If we look at the markup rendered by the ActionLink method, we will see the following code:
<A data-ajax = "true" data-ajax-method = "Get" data-ajax-mode = "replace" data-ajax-update = "# dailydeal" href =" /Home/DailyDeal "> click me </a>
(2) A notable feature of non-intrusive JavaScript is that it does not contain any JavaScript code in HTML, that is, it cannot be seen in HTML, if you take a closer look, you will find that all the settings specified in ActionLink are encoded into the features of HTML elements, and most of these encoding features have a data-prefix, which is usually called the data-feature.
(3) The HTML 5 specification retains the data-feature for private applications. In other words, the web browser will not try to explain the data-feature content, so you can safely give your data to it, the data does not affect page display or rendering.
(4) Add the jquery. unobtrusive-ajax file to the application to search for specific data-features, and then manipulate the elements to make them behave differently.
(5) All ASP. net mvc ajax features use the data-feature.
4. Ajax forms
(1) The following is another scenario. You need to add an artist search function to the user on the homepage of the music store because user input is required, therefore, a form label must be placed on the page, but this is not a common label, but an asynchronous form. Let's take a look at the following code:
Copy codeThe Code is as follows:
@ Using (Ajax. BeginForm ("ArtistSearch", "Home", new AjaxOptions
{
InsertionMode = InsertionMode. Replace,
HttpMethod = "GET ",
OnFailure = "searchFailed ",
LoadingElementId = "ajax-loader ",
UpdateTargetId = "searchresults ",
}))
{
<Input type = "text" name = "q"/>
<Input type = "submit" value = "Search"/>

}

(2) In the form to be rendered, When you click the submit button, the browser will send an asynchronous GET request to the ArtistSearch operation of the controller HomeController, note that the above Code has specified LoadingElementId as one of the options. When an asynchronous request is executed, the client framework automatically displays this element. Generally, A fine-tuned box with animation effects will appear inside the element to inform the user of some processing in the background. In addition, there is an OnFailure option, which includes many parameters, you can set them to capture various client events from Ajax requests, such as OnBegin, OnComplete, OnSuccess, and OnFailure. You can assign these parameters a JavaScript function name. When an event is triggered, when this function is called, the code above specifies a JavaScript function for OnFailure. The Code is as follows:
<Script type = "text/javascript">
Function searchFailed (){
$ ("# Searchresults" ).html ("Sorry, there is a problem with the query ");
}
</Script>
(3) If the server code returns an error, it means that all the AJAX-assisted methods fail to be executed. At this time, you may want to capture the OnFailure event, if you click the "search" button and the page does not respond, we may be confused. As with the previous code, an error message is displayed, at least let them know that we have done our best.
(4) the output of inform is similar to that of ActionLink. Finally, when you click Submit to submit a form, the server receives an Ajax request, the response may be in any format. When the client receives a response from the server, the non-intrusive script will put the corresponding content into the Dom.
(5) In this example, the Controller operation needs to query the database and render a segment view. In addition, the operation also returns plain text, but also wants to put the artist in a list. Therefore, write the following method code in HomeControler:
Copy codeThe Code is as follows:
Public ActionResult ArtistSearch (string q)
{
Var artists = GetArtists (q );
Return PartialView (artists );
}

Private List <Artist> GetArtists (string q)
{
Return storeDB. Artists. Where (a => a. Name. Contains (q). ToList ();
}

(6) This branch view uses the model to build a list. It is located in the ArtistSearch. cshtml view under the Views/Home folder of the project.

Copy codeThe Code is as follows:
@ Model IEnumerable <MvcMusicStore. Models. Artist>
@{
Layout = null;
}
<! DOCTYPE html>
<Html>
<Head>
<Title> ArtistSearch </title>
</Head>
<Body>
<Div id = "searchresults">
<Ul>
@ Foreach (var item in Model)
{
<Li> @ item. Name </li>
}
</Ul>
</Div>
</Body>
</Html>

5. AJAX settings in the web. config file
(1) by default, non-intrusive JavaScript and client verification are performed in ASP.. net mvc application is enabled. Then, we can use the web. the settings in the config file change these actions if you open the web under the root directory of the new application. in the config file, the following appSettings configuration node is displayed:
<Deleetask>
<Add key = "webpages: Version" value = "1.0.0.0"/>
<Add key = "ClientValidationEnabled" value = "true"/>
<Add key = "UnobtrusiveJavaScriptEnabled" value = "true"/>
</AppSettings>
(2) If you want to disable any feature of these two features in the entire application, you only need to change the value of the response feature to false. In addition, you can also control these settings by view. The HTML auxiliary methods EnableClientValidation and EnableUnobtrusiveJavaScript override these configuration settings in a specific view.
(3) because existing custom scripts depend on the Microsoft AJAX library rather than the Jquery library, the main reason for Disabling these features is to maintain backward compatibility of applications.

Note: In the next MVC blog, we will focus on another built-in AJAX feature of the ASP. net mvc Framework-Support for client verification.
Author: Han Yinglong
Source: http://www.cnblogs.com/hanyinglong

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.