ASP. MVC4 + Oracle + Easyui + Bootstrap Chapter II-improving website performance with Ajax
This article link: http://www.cnblogs.com/likeli/p/4236723.html
Article collection: http://www.cnblogs.com/likeli/category/651581.html
1. Partial view of MVC rendering
Requesting HTML tags from the server to update the contents of a Web page is called "partial rendering", which is the basic process of Ajax.
Partial rendering techniques include sending asynchronous requests to the server, and the server returning data that contains HTML code into the specified page area. This method is very efficient and simple.
in ASP. NET MVC, partial rendering is treated as a normal request: The request is routed to a specific controller, and the controller executes the specific operational logic.
Common rendering and rendering partial views differ: The usual rendering method is to use a controller. The View () Help method returns Viewresult, while partial rendering requires calling the Controller.partial () helper method to return the Partialviewresult object. This is similar to Viewresult, where Partialviewresult renders only the content that contains the view and does not render the perimeter layout.
1) The controller calls the Controller.view () method:
1 return View ("Auction", Auction);
The end result is full page rendering.
2) The controller calls the Controller.partialview () method:
1 return Partialview ("Auction", acution);
Partial rendering replaces view () with the Partialview () method, as well as the others. The only difference is that Partialviewresult renders only HTML tag content and does not include the contents of the perimeter layout and master pages. Other include razor syntax, HTML, URL helper classes are all used as well.
Note, however, that because some views do not include a perimeter layout, the CSS or JavaScript external files must be referenced directly in the partial view.
This part of the class can be implemented quickly using the jquery load () method.
1 function Showauctino (ID) 2 {3 $ ("#content"). Load ("/auction/partialauction/" +ID); 4 }
The above code, if used Urlhelper, can be written like this: ' @Url ("Partialauction", "Auction") ' + ID
2. JavaScript rendering
In fact, from the above part of the view rendering can be seen, this rendering method is a waste of resources, it is obvious that some of the content is completely unnecessary in the server to create and pass back, JS enough to complete.
However, there are two mandatory conditions for using client-side rendering:
1) The server can produce serialized data
2) The client knows how to convert these serialized data into standard HTML code
Here, using AJAX to request data, ASP. NET MVC provides support for native JSON, using Jsonresult to manipulate the result object. Therefore, we can use the Controller.json () method directly to create a jsonresult that contains serializable objects .
1 return Json (Action,jsonrequestbehavior.allowget);
Then the reply message returned by this controller contains the serialized JSON format data.
The second parameter in the above code is required because MVC does not allow get-way HTTP requests for JSON data by default. This avoids the risk of JSON hijacking. Therefore, you need to set the Allow GET request JSON here.
However, the best practice is to avoid such security vulnerabilities by using attribute tags to restrict the Post method to submit requests only.
1 [HttpPost] 2 Public ActionResult jsonauction (int ID)3{4 ... 5 return Json (acution); 6 }
3. Client templates
Here, the JSON data has been requested back, then we need to process the client, here using the client template, which is the template engine to render. Of course, if the content is not complex, you can simply splice the string to the output.
Here I am using the Laytpl template rendering engine (http://sentsin.com/layui/laytpl/):
1 //The first step: Write a template. You can use a script tag to store the template, such as:2<script id= "Demo" type= "Text/x-template" >34<ul>5{{# for(vari = 0, len = d.list.length; i < Len; i++){ }}6<li>7<span> Name: {{D.list[i].name}}</span>8<span> City: {{d.list[i].city}}</span>9</li>Ten {{# } }} One</ul> A</script> - - //Step Two: Build the view. Used to render the rendered result. the<div id= "View" ></div> - - //Step Three: Rendering Templates - functionupdateauctioninfo (ID) + { - $.ajax ({ +URL: "/auction/jsonauction/" + ID, ASucction:function(Result) { at varGETTPL = document.getElementById (' demo '). InnerHTML; -LAYTPL (GETTPL). Render (Result,function(HTML) { -document.getElementById (' View '). InnerHTML =html; - } - }) -}
So here, the above code has completed an AJAX performance improvement function, but this can be improved. We continue to ...
As an MVC framework, it is important to "detach the focus" and, under normal circumstances, the application logic of MVC should not be bound to the view. In the example code above, there is this situation, to the content of the same view output, we use Partialview, view, we are doing the same action-output HTML tag content, the only difference is that the content returned is not the same.
So we can figure out how to subtract these repetitive logic codes, and fortunately, MVC provides a request.isajaxrequest () extension method that can help us verify that the current request is Ajax. So the inspiration came.
1Public ActionResult Auction (intID)2 {3 //Get Data source4 ...5 if(Request.isajaxrequest ())6 {7 returnPartialview ("Auction", auction);8 }9 ElseTen { One returnView ("Auction", auction); A } -}
Then, after this modification, the auction controller can respond to both requests at the same time: HTTP get and Ajax, while the logic code does not change.
4. Processing JSON
Here, my needs are a little bit different, and I want to be able to request the full HTML code when I ask for it, and I want to be able to request JSON data. Do how
This MVC has no way, and does not provide a method like the above to verify the Ajax method, to verify whether to request JSON. However, craved in fact also difficult to fall the Intelligent program Ape. At the time of the AJAX request, plus a parameter, specify that the request is JSON. Example:/AUCTIONS/AUCTION/1? Isjson=json
View the source code, found that Ajaxrequestextensions is a static class, cannot inherit.
Then, extend this self-defined method of validating whether to request JSON:
1 Public Static classjsonrquestextensions2 {3 Public Static BOOLIsjsonrquest ( Thishttprequestbase request)4 {5 return string. Equals (request["Isjson"],"Json");6 }7}
1 if (Request.isjsonrquest ()) 2 {3 return Json (auction); 4 }5 else6 {7 return View ("auctino", Auction); 8 }
This will do, and then integrate the previous written content:
1 if(Request.isjsonrquest ())2 {//json Request3 returnJson (auction);4 }5 Else if(Request.isajaxrquest ())6 {//ajax Request7 returnPartialview ("Auxtion", auction);8 }9 ElseTen {//default use of layout requests One returnView ("Auctino", auction); A}
With a series of logic judgments above, a controller action is completed to render the partial view and judge the logic of the JSON request's return data.
Speaking of which, there is a new thing to introduce: filters. Specifically, it should be the operation of the filter .
Forgive me once again shameless pirates of a picture (although the figure is drawn by myself), this figure refers to the "ASP. NET MVC5 Framework Disclosure" diagram, here to illustrate the implementation of this filter.
Action filters involve the use of actionfilter types. As shown, all actionfilter types implement the Iactionfilter interface, and the two methods Onactionexecution and onactionexecuted of the interface are called before and after the target action method executes.
Since there is a call before the action method executes, then we can make a fuss here.
Rewrite the onactionexecuted method to add Ajax, JSON, and other request-way judgment logic.
In this way, an action filter is constructed, and the action filter is to reuse the unified logic rules on multiple controllers .
5. Finally
Good Dalat, to use Ajax to improve website performance and interaction is basically done, of course, the actual operation is not so simple, here only to get started.
For example, if it's a complex JSON, you need to do a lot of work. The next chapter goes on to get to this, basically talking about how complex JSON operates, how to improve the efficiency of JSON delivery, cross-domain AJAX requests, and so on.
6. Reference documents
The "ASP. NET MVC5 framework", "ASP. NET MVC4 Web Programming"
ASP. MVC4 + Oracle + Easyui + Bootstrap Chapter II