ASP. NET mvc4 in action learning notes-wave 6 [Ajax in ASP. net mvc] [2/3]

Source: Internet
Author: User
Tags actionlink

Read the sixth wave of Navigation:

ASP. NET mvc4 in action learning notes-wave 6 [Ajax in ASP. net mvc] [1/3]

ASP. NET mvc4 in action learning notes-wave 6 [Ajax in ASP. net mvc] [3/3]

Original:ASP. net mvc 4 in action

Hello everyone!

I amYan yangfangzhuFirst, I declare that I am not a translator and I am a post-90 personProgramMember.

The original text of this wave contains some basic jquery tutorials, Which I omitted in this wave. if you do not have the foundation of jquery, I don't think you need to continue reading it. I suggest you first understand jquery-related content! Thanks to your support, I plan to improve the quality of my blog. I learned a little front-end knowledge a few days ago, so the mvc4 series of blogs were only published today. I apologize for the last few days of the plan.

Honestly, this blog has a lot of content ~

 

7.2ASP. net mvc Ajax helpers

So far, we have all looked at how to write JavaScript on the client.CodeSend data to the server and retrieve data from the server. Now let's take a look at using ASP. net mvc to operate Ajax. We use Ajax helpers.

At the beginning, we will look at several Ajax Methods and Their Association with jquery or Javascript libraries. They can also achieve the effect of manually writing part of jquery code.

These helpers used areAjaxhelperClass extension method. This class can be automatically used to generate HTML tags after data is sent and obtained through Ajax. The helpers are as follows:

(It doesn't matter if you use English here. Don't blame me for it, because I don't think it's easy to understand the translation. It's better to write a demo to understand it)

With these technologies, Ajax helper uses the Javascript library for real Ajax requests. Instead of binding to any specific library, these tags use an adapter layer that knows how to send Ajax requests. ASP. net mvc has an adapter that can adjust Microsoft Ajax and jquery. Which of the two is used depends on the configuration of the application.

When you create a new ASP. netmvc project, the following line of code appears in the web. config on the outermost layer.

If the setting is enabled (true), the tag (markup) generated by Ajax helper will useArticleThe code in section 7.1 is the same, so you can use the unobtrusive JavaScript method to achieve Ajax effect. However, when the settings are disabled (false), these helpers will use the Microsoft Ajax library to generate a markup. We recommend that you set it to true. In section 7.2.4, we will discuss what will happen if it is set to false.

Note: Except. you can also set unobtrusivejavascriptenabled to true in config. set htmlhelper in application_start of asax file. the unobtrusivejavascriptenabled attribute is set to true as a global setting.

 

 

Based on whether unobtrusivejavascriptenabled is true or false, Asp. net MVC's Ajax helpers will generate a markup compatible with a specific adapter layer, which knows how to accept these labels and then calls the appropriate JavaScript library for actual work.

 

 

The following are ASP. net mvc Ajax helpers and

Diagram of the Javascript Library

 

 

 

 

 

 

 

 

 

 

7.2.1Ajax. actionlink

Next let's useActionlinkAjax helper, modify the index. cshtml File Code as follows:

Next we will use actionlink Ajax helper, and we will not modify the controller. We will modify the index. cshtml view. You can compare the actionlink of HTML with the actionlink of Ajax:
The first parameter-the text to be displayed, the second parameter-the action name in the request's controller. In the Ajax actionlink, there is an ajaxoptions parameter. Here the code means, replace the data after successful requests and replace all the HTML code in the DOM element whose ID is privacy.
Insertionmode is an enumeration. You can try it yourself.
 
1:@{
 
2:Viewbag. Title ="Index";
3:}
 
4:@ Section head {
 
5:<SCRIPT type ="Text/JavaScript"Src ="@ URL. Content ("~ /Scripts/ajaxdemo. js")"> </SCRIPT>
 
6:<SCRIPT type ="Text/JavaScript"Src ="@ URL. Content ("~ /Scripts/jquery. unobtrusive-ajax.js")"> </SCRIPT>
 
7:}
 
8: 
 
9:@ Html. actionlink ("Show the Privacy Policy",
10:"Privacypolicy",Null,New{Id ="Privacylink"})
 
11:<Br/>
 
12:@ Ajax. actionlink ("Show the privacy policy2",
 
13:"Privacypolicy",NewAjaxoptions {
 
14:Insertionmode = insertionmode. Replace, updatetargetid ="Privacy" 
 
15:})
16:<Div id ="Privacy"> </Div>

Press F5 to run the program. We can see that the HTML code generated by the Ajax assistant is as follows. We can see the familiar unobtrusive JavaScript code.

    A   data-Ajax   =" true "  data-Ajax-mode 
     = "replace"   data-Ajax-update   =" # privacy "  href   ="/ajaxhelper/privacypolicy"    show the privacy policy2    A    

When the page is loaded, the script in the jquery-unobtrusive.ajax looks for all links that contain the data-Ajax attribute, finds it, and binds the click event. Similarly, if the browser disables JavaScript, the link serves as a normal link and returns to the non-Ajax (no Ajax) action.

 HTML5 data attributes

Data-* attributes, such as data-Ajax and data-Ajax-Update, are both famous HTML5 attributes and provide additional metadata (metadata) to implement the annotate HTML element. Although you provide information about Ajax requests, you can write the metadata you want to access on the client)

Although these custom attributes are part of the HTML5 detailed guide, they can work normally without any problem on browsers that do not support HTML (such as IE6.

7.2.2Ajax. beginform

 

 

You can also use ASP. NET'sAjax. beginformHelper can also asynchronously submit form data.

Open this page and we will continue to write code

After the code is added, the Code is as follows:

 
@ Model ienumerable <String>
 
 
@{
 
Viewbag. Title ="Index";
 
}
 
@ Section head {
 
<SCRIPT type ="Text/JavaScript"Src ="@ URL. Content ("~ /Scripts/jquery. unobtrusive-ajax.js")"> </SCRIPT>
 
}
 
 
 
 
 
<H4> comments </H4>
 
 
 
<Ul id ="Comments">
 
@Foreach(VAR commentInModel)
 
{
 
<Li> @ comment </LI>
 
}
</Ul>
 
 
 
@Using(Ajax. beginform ("Addcomment",NewAjaxoptions {updatetargetid ="Comments", Insertionmode = insertionmode. insertafter }))
 
{
 
@ Html. textarea ("Comment",New{Rows = 5, cols = 50 })
 
<Br/>
 
<Input type ="Submit" Value="Add Comment"/>
 
}
 
 
 
 
 
@ * @ Html. actionlink ("Show the Privacy Policy",
"Privacypolicy",Null,New{Id ="Privacylink"})*@
 
<Br/>
 
@ Ajax. actionlink ("Show the privacy policy2",
 
"Privacypolicy",NewAjaxoptions
 
{
 
Insertionmode = insertionmode. Replace,
 
Updatetargetid ="Privacy"
 
})
 
 
 
 
 
<Div id ="Privacy"> </Div>

Like the HTML. beginform we see in Chapter 2, this Ajax. beginform is also wrapped in using, and beginform creates a form. End with}, equivalent to <form/>

We reload the two parameters of beginform-the action name in the first controller. If the controller is not written, it indicates the Controller corresponding to the current view. The ajaxoptions object is the same as that of Ajax. actionlink.

Add the following code to ajaxhelperscontroller:

Static ReadonlyList <String> _ Comments =NewList <String> ();
 
 
 
PublicActionresult index ()
 
{
 
ReturnView (_ Comments );
 
}
 
 
 
[Httppost]
 
PublicActionresult addcomment (StringComment)
 
{
 
_ Comments. Add (comment );
 
 
If(Request. isajaxrequest ())
 
{
 
Viewbag. Comment = comment;
 
ReturnPartialview ();
 
}
 
 
 
ReturnRedirecttoaction ("Index");
 
}
 
 
 
PublicActionresult privacypolicy ()
 
{
 
If(Request. isajaxrequest ())
 
{
 
ReturnPartialview ();
}
 
 
 
ReturnView ();
 
}

Then, copy addcomment. cshtml under the customajax folder to the ajaxhelper folder.

When running this page, the principles are the same. Although the form is modified by the additional data-Ajax attribute, it is similar to actionlink. The following is:

:

In this way, the progressive form enhancement mode (progressive enhancement) has been completed. The previously completed html. actionlink has become Ajax. actionlink, and now the form transition is complete. The form has HTML. beginform becomes Ajax. beginform, using jquery. unobtrusive-Ajax script, the form will be submitted in the form of Ajax, but if the client disables JavaScript, this form will send a POST request in a normal form.

7.2.3Ajax options

In several sections, you can see that both actionlink and beginform Ajax helper have ajaxoptions objects, which indicate how Ajax results are processed. It defines the following attributes:

If you have jquery experience before, you can understand many of them.

Except loadingelementduration, all these options were available in the previous ASP. NET MVC2. However, these options are different in the tab of the page. As you can see, in HTML elements, these options are all generated in the form of data-*. However, in MVC2, they are inserted into the page, in a more unobtrusive way.

 

7.2.3Different from ASP. net mvc in previous versions

Although Ajax helpers is already part of MVC in mvc1, jquery is the default one. In earlier versions of the framework, these helpers all use Microsoft Ajax library and do not use unobtrusive to generate JavaScript. You can change the unobtrusivejavascriptenabled attribute under the deleettings node under the Web. config node to false to restore the previous version of the framework.

For example, if this parameter is set to true, change unobtrusivejavascriptenabled to false to run the project:

The code generated after Ajax. actionlink is used is as follows:

After setting unobtrusivejavascriptenabled to false, the data-Ajax attribute is no longer used. All metadata is replaced by the onclick event. To make the program run correctly, the framework requires that you reference microsoftajax. JS and microsoftmvcajax. compared with unobtrusive-style code, JS is not readable and intuitive, and breaks the unobtrusive JavaScript principle.

If you are upgrading your previous ASP. net mvc version, you need to keep these actions. To improve compatibility, you need to set unobtrusivejavascriptenabled to false. However, in other cases, setting unobtrusivejavascriptenabled to true is the best, because it is more intuitive and readable When HTML is generated, and Microsoft attaches great importance to Ajax's unobtrusive writing method, and is being updated and researched.

 

 Blog comments

In order to give readers a better reading experience, we plan to separate the content of each chapter and make the reading more comfortable.

At the same time, I can write a little bit every day, and upload a little bit every day, instead of having to write each chapter of blog at once, instead of publishing it at once

There is too much content, so every time the reader learns and views, there will be more downloads. considering this, this blog is written here ..

Good night, everybody! Because the source code file is too large, it will not be released first. After all the blogs in this chapter are completed, it will be released once.

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.