asp.net MVC using AJAX-Assisted solutions _ Practical Tips

Source: Internet
Author: User
Tags configuration settings actionlink

Foreword: We have briefly described how the MVC jquery, because if we use Ajax we have to understand jquery, this blog we will have a general understanding of how ASP.net mvc use Ajax helper method, this blog is my reading notes, if there is no good writing , but also invited friends to put forward, we learn together.
1. Preparatory work
(1) When MVC was just beginning to learn, we needed to introduce the asp.net of HTML in the MVC framework, but this kind of article is now very much, and the personal feeling is very simple, so did not write notes, I am not here to introduce.
(2) asp.net the HTML helper method in the MVC framework, we can use HTML-assisted methods to create forms and links to controller actions, and include a set of Ajax-assisted methods in the ASP.net MVC framework that can also be used to create forms and connections to controller operations. But the difference is that they are done asynchronously, and when using these helper methods, you do not have to write any scripting code to implement the asynchronous nature of the program.
(3) In the background, these Ajax helper methods rely on the jquery extension of non-intrusive MVC, and if you use these helper methods, you need to introduce script files Jquery.unobtrusive-ajax.js, as to how to quote me in the last blog has said, here is not to post code.
The ActionLink method of 2.Ajax
(1) In the Razor view, Ajax accessibility methods can be accessed through Ajax properties, and similar to HTML helper methods, most Ajax helper methods on Ajax properties are extension methods (except for the Ajaxhelper type).
(2) The ActionLink method of Ajax properties creates an anchor tag with asynchronous behavior. Now we can change it on the MVC3.0 Musicstore project that Microsoft releases, who without this project can add the underground group, and then share the project in the group sharing. Add the following code in the View "views/home/index.cshtml".

Copy Code code 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 invoked asynchronously, similar to an HTML helper method with the same name. For HTML helper methods and Ajax helper methods, the significantly different is the Ajaxoptions parameter, which specifies the method of sending requests and processing the results of the server return, including options for handling errors, displaying load elements, displaying a confirmation dialog box, and so on. In order to get a response from the server, you need to add a dailydeal action on the controller HomeController, as follows:

Copy Code code as follows:

Public ActionResult Dailydeal ()
{
var album = Getdailydeal ();
Return Partialview ("_dailydeal", album);
}
Private Album Getdailydeal ()
{
Return StoreDB.Albums.OrderBy (a => a.price). A ();
}

(4) The return value of the target operation of the Ajax operation connection is plain text or HTML. The following razor code is in the _dailydeal.cshtml file under the project's Views/home folder.

Note: Ajax.actionlink generated content can get a response from the server, and can directly migrate new content to the page, then why? Here we will explain how asynchronous operation connections work.
3.HTML5 characteristics
(1) If we look at the markup that the ActionLink method renders, we'll 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) The notable feature of Non-intrusive JavaScript is that it does not contain any JavaScript code in HTML, which means that script code is not visible in HTML, and if you look closely you will find that all the settings specified in ActionLink are encoded into the attributes of the HTML element. And most of these encodings have data-prefixes, often called data-properties.
(3) The HTML 5 specification retains the data-attribute for private applications, in other words, the Web browser does not attempt to explain the content of the data-feature, so you can safely give it to the data without affecting the display or rendering of the page.
(4) The purpose of adding a Jquery.unobtrusive-ajax file to an application is to look for a specific data-feature and manipulate the elements to behave differently.
(5) All ASP.net MVC ajax features use the data-feature.
4.Ajax form
(1) Below we implement another situation, to the music Store's homepage for users to add a search artist's function, because the user needs input, so you must put a form tag on the page, but this is not a normal label, but an asynchronous form. Let's take a look at the following code:

Copy Code code 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) Again to render the form, when the user clicks the Submit button, the browser sends an asynchronous GET request to the controller HomeController Artistsearch operation, noting that the above code has specified Loadingelementid as one of the options. When an asynchronous request is executed, the client framework automatically displays the element, and in general, an animated spinner appears inside the element to tell the user that some processing is being done in the background, and there is also a onfailure option, which includes many parameters, They can be set up to capture various client events from Ajax requests, such as Onbegin,oncomplete,onsuccess and onfailure, that can give these parameters a name for a JavaScript function that is invoked when the event is triggered, The code above specifies a JavaScript function for OnFailure, as follows:
<script type= "Text/javascript" >
function searchfailed () {
$ ("#searchresults"). HTML ("Sorry, query is problematic");
}
</script>
(3) If the server code returns an error, which means that the Ajax helper method has failed, at this point, you may want to capture the OnFailure event, if the user clicks the "Search" button and the page does not respond, we may be confused, as the previous code does, You can display an error message, or at least let them know that we have done our best.
(4) The output of the auxiliary method BeginForm is similar to the auxiliary method ActionLink, and finally, when the user clicks the Submit button to submit the form, the server receives an AJAX request and may respond in any format, when the client receives a response from the server side, Non-intrusive scripting will put the appropriate content into the DOM.
(5) For this example, the controller operation needs to query the database and render a partial view, in addition, the operation will return plain text, but also want to put the artist into a list, therefore, in Homecontroler write the following method code:
Copy Code code 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) The partial view builds the list using the model, which is located under the Views/home folder of the project's view artistsearch.cshtml.

Copy Code code as follows:

@model ienumerable<mvcmusicstore.models.artist>
@{
Layout = null;
}
<! DOCTYPE html>
<title>ArtistSearch</title>
<body>
<div id= "SearchResults" >
<ul>
@foreach (var item in Model)
{
<li> @item. Name</li>
}
</ul>
</div>
</body>

Ajax settings in the 5.web.config file
(1) By default, non-intrusive JavaScript and client-side validation are enabled in the ASP.net MVC application, and then We can change these behaviors through the settings in the Web.config file, and if you open the Web.config file under the root of the new application, you will see the following appsettings configuration node:
<appSettings>
<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 of these attributes in the entire application, simply modify the value of the response attribute to False, and you can control the settings by view, as well. HTML helper Methods Enableclientvalidation and Enableunobtrusivejavascript override these configuration settings in a specific view.
(3) Because existing custom scripts are dependent on Microsoft Ajax libraries rather than jquery libraries, the primary reason for disabling these features is to maintain application backward compatibility.

Note: The next MVC Blog We will turn our attention to another built-in Ajax feature of the ASP.NET MVC framework-support for client-side validation.
Author: Han Guanlong
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.