Asp.net MVC source code analysis-renderaction and renderpartial

Source: Internet
Author: User

End of the previous ArticleArticleAsp.net MVC source code analysis-actionresult razorview. renderview I believe you should understand the general process of MVC. Now let's take a look at the most frequently used methods in MVC development. What I think isHtml. renderaction and HTML. renderpartialRight. Let's make it simple: renderpartial andPartial

Public static voidRenderpartial(This htmlhelper, string partialviewname, object model, viewdatadictionary viewdata ){
Htmlhelper.Renderpartialinternal(Partialviewname, viewdata, model,Htmlhelper. viewcontext. Writer, Viewengines. Engines );
}

Public static mvchtmlstring partial (this htmlhelper, string partialviewname, object model, viewdatadictionary viewdata) {
using ( stringwriter writer = new stringwriter (cultureinfo. currentculture ) {
htmlhelper. renderpartialinternal (partialviewname, viewdata, model, writer , viewengines. engines);
return mvchtmlstring. create (writer. tostring () ;
}< BR >}

From here we can knowRenderpartial andPartial: The returned data streams are inconsistent. One is the current writer and the other is the new writer. Of course, the new writer can easily return the character text..

Renderpartialinternal definition and CoreCodeAs follows:

Internal virtual voidRenderpartialinternal(String partialviewname, viewdatadictionary viewdata, object model, textwriter writer, viewenginecollection ){

Viewcontext newviewcontext = new viewcontext (viewcontext, viewcontext. View, newviewdata, viewcontext. tempdata, writer );
Iview view = findpartialview (newviewcontext, partialviewname, viewenginecollection );
View. Render (newviewcontext, writer );
}

Check whether it is very simple, and the key here is findpartialview. Find the view and call its render method,FindpartialviewThe core code is like,Viewengineresult result = viewenginecollection. findpartialview (viewcontext, partialviewname); we know from the previous articleFindviewThe logic is consistent with that of findpartialview.

Now let's take a look at renderactionAnd action Method

Public static mvchtmlstring action (this htmlhelper, string actionname, string controllername, routevaluedictionary routevalues) {
using ( stringwriter writer = new stringwriter (cultureinfo. currentculture) ) {
actionhelper (htmlhelper, actionname, controllername, routevalues, writer );
return mvchtmlstring. create (writer. tostring () );
}< BR >}< br>

Public static void renderaction (this htmlhelper, string actionname, string controllername, routevaluedictionary routevalues) {
actionhelper (htmlhelper, actionname, controllername, routevalues, htmlhelper. viewcontext. writ er );
}

Internal static void actionhelper (htmlhelper, string actionname, string controllername, routevaluedictionary routevalues, textwriter) {If (htmlhelper = NULL) {Throw new partition ("htmlhelper ");} if (string. isnullorempty (actionname) {Throw new argumentexception (mvcresources. common_nullorempty, "actionname");} routevaluedictionary additionalroutevalues = route Values; routevalues = mergedictionaries (routevalues, htmlhelper. viewcontext. routedata. values); routevalues ["action"] = actionname; If (! String. isnullorempty (controllername) {routevalues ["controller"] = controllername;} bool usingareas; virtualpathdata VPD = htmlhelper. routecollection. getvirtualpathforarea (htmlhelper. viewcontext. requestcontext, null/* name */, routevalues, out usingareas); If (VPD = NULL) {Throw new invalidoperationexception (mvcresources. common_noroutematched);} If (usingareas) {routevalues. remove ("area"); I F (additionalroutevalues! = NULL) {additionalroutevalues. Remove ("area") ;}} if (additionalroutevalues! = NULL) {routevalues [childactionvalueprovider. childactionvalueskey] = new dictionaryvalueprovider <Object> (additionalroutevalues, cultureinfo. invariantculture);} routedata = createroutedata (VPD. route, routevalues, VPD. datatokens, htmlhelper. viewcontext); httpcontextbase httpcontext = htmlhelper. viewcontext. httpcontext; requestcontext = new requestcontext (httpcontext, route Data); childactionmvchandler handler = new childactionmvchandler (requestcontext); httpcontext. server. execute (httphandlerutil. handler (handler), textwriter, true/* preserveform */);} Private Static routedata createroutedata (routebase route, routevaluedictionary routevalues, routevaluedictionary datatokens, viewcontext parentviewcontext) {routedata = new routedata (); foreach (Keyvaluepair <string, Object> kVp in routevalues) {routedata. values. add (kVp. key, kVp. value);} foreach (keyvaluepair <string, Object> kVp in datatokens) {routedata. datatokens. add (kVp. key, kVp. value);} routedata. route = route; routedata. datatokens [controllercontext. parent_action_viewcontext] = parentviewcontext; return routedata;} Private Static routevaluedictionary mergedictionaries (Params ROU Tevaluedictionary [] dictionaries) {// merge existing route values with the user provided values var result = new routevaluedictionary (); foreach (routevaluedictionary dictionary in dictionaries. Where (D => D! = NULL) {foreach (keyvaluepair <string, Object> kVp in dictionary) {If (! Result. containskey (kVp. Key) {result. Add (kVp. Key, kVp. Value) ;}} return result ;}

The difference between renderaction and action is the same as that between renderpartial and partial. One is to return the content to the current stream and the other is to return a string.

Htmlhelper. viewcontext. routedata. values this values contains all our routing information, typically action, Controller,There is such an IF (! String. isnullorempty (controllername) {routevalues ["controller"] = controllername;}. This sentence explains that if we call renderpartial without passing in the controller, it will be the current controller by default.Now let's take a look at how the getvirtualpathforarea method obtains virtualpathdata.

Internal static virtualpathdata getvirtualpathforarea (this routecollection routes, requestcontext, string name, routevaluedictionary values, out bool usingareas) {If (routes = NULL) {Throw new argumentnullexception ("Routes");} If (! String. isnullorempty (name) {// The route name is a stronger qualifier than the area name, so just pipe it through usingareas = false; return routes. getvirtualpath (requestcontext, name, values);} string targetarea = NULL; If (values! = NULL) {object targetarearawvalue; If (values. trygetvalue ("area", out targetarearawvalue) {targetarea = targetarearawvalue as string;} else {// set target area to current area if (requestcontext! = NULL) {targetarea = areahelpers. getareaname (requestcontext. routedata) ;}}// need to apply a correction to the RVD if areas are in use routevaluedictionary correctedvalues = values; routecollection filteredroutes = routes, targetarea, out usingareas ); if (usingareas) {correctedvalues = new routevaluedictionary (values); correctedvalues. remove ("area");} virtualpathdata VPD = filteredroutes. getvirtualpath (requestcontext, correctedvalues); Return VPD ;}

the name we pass in is null by default, and usingareas is = false. Here, we first get the area, and the priority is: (1) whether the current routevaluedictionary contains area, (2) the current request requestcontext. routedata. whether datatokens contains area, (3) requestcontext. routedata. route. whether datatokens contains area . The code of my areahelpers is as follows:

Internal static class areahelpers {public static string getareaname (routebase route) {iroutewitharea routewitharea = route as iroutewitharea; If (routewitharea! = NULL) {return routewitharea. area;} route castroute = route as route; If (castroute! = NULL & castroute. datatokens! = NULL) {return castroute. datatokens ["area"] as string;} return NULL;} public static string getareaname (routedata) {object area; If (routedata. datatokens. trygetvalue ("area", out area) {return area as string;} return getareaname (routedata. route );}}

Filterroutecollectionbyarea is used to remove all route information that is different from the area in the current route information. To build new route information..
Private Static routecollection filterroutecollectionbyarea (routecollection routes, string areaname, out bool usingareas ){
If (areaname = NULL ){
Areaname = string. empty;
}
Usingareas = false;
Routecollection filteredroutes = new routecollection ();
Using (routes. getreadlock ()){
Foreach (routebase route in routes ){
String thisareaname = areahelpers. getareaname (route )?? String. empty;
Usingareas | = (thisareaname. length> 0 );
If (string. Equals (thisareaname, areaname, stringcomparison. ordinalignorecase )){
Filteredroutes. Add (route );
}
}
}
// If areas are not in use, the filtered route collection might be incorrect
Return (usingareas )? Filteredroutes: routes;
}
Last call Getvirtualpath of routecollection Method. The getvirtualpath method of routecollection is actually the base2.getvirtualpath method of each routebase in the loop call.

Foreach (routebase base2 in this)
{
 Virtualpathdata virtualpath = base2.getvirtualpath (requestcontext, values );
If (virtualpath! = NULL)

{
Virtualpath. virtualpath = This. normalizevirtualpath (requestcontext, virtualpath. virtualpath );
Return virtualpath;
}
}

We know that routebase is actually a route instance. Let's take a look at its getvirtualpath method.

Boundurl url = This. _ parsedroute. BIND (requestcontext. routedata. values, values, this. defaults, this. Constraints) is actually the bind method of parsedroute called,

The boundurl returned by this bind method has a special attribute return New boundurl {Url = builder. tostring (), Values = acceptedvalues };

Combined with the integer method, we know that it Concatenates the routevalues we passed in when calling renderaction into a URL string. For example:

Unfortunately, this virtualpath attribute is not used in MVC.Because we do not need to take the value here. The true value depends on the following sentence:

 Routevalues [childactionvalueprovider. childactionvalueskey] = new dictionaryvalueprovider <Object> (additionalroutevalues, cultureinfo. invariantculture );

This is to save the imported routevalues for later calling.

Let's take a look at the key implementation code of childactionvalueprovider:

Public override valueproviderresult getvalue (string key ){
Valueproviderresult explicitvalues = base. getvalue (childactionvalueskey );
If (explicitvalues! = NULL ){
Dictionaryvalueprovider <Object> rawexplicitvalues = explicitvalues. rawvalue as dictionaryvalueprovider <Object>;
If (rawexplicitvalues! = NULL ){
Return rawexplicitvalues. getvalue (key );
}

}
Return NULL;
}

Obtain routevalues through childactionvalueskey, and then set the value based on the key in routevalues. I think you should understand why the defamodelmodelbinder will use the bindsimplemodel method in renderaction,I think you should understand why the defaultmodelbinder method follows the bindsimplemodel method in renderaction, but ifRoutevalues does not pass the parameters we need, and our parameters are a complex type, so we will go throughThe bindcomplexmodel method returns a null value for a simple type. Whether it is a simple type determines whether it can be converted to a string..

The createroutedata method is nothing special,Routedata. datatokens [controllercontext. parent_action_viewcontext] = parentviewcontext; use the new action as the subaction.

There is nothing to say about httphandlerutil. wrapforserverexecute,Package the current childactionmvchandler into a serverexecutehttphandlerwrapper. However, serverexecutehttphandlerwrapper inherits from the page class..

SlaveHere we know that the renderaction is to initiate a handler request processing and the renderpartial is only a rendering attempt, so the renderpartial performance is much higher..

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.