Foreword: Before studying a lot of bootstrap component, Blogger is in the mind idea: whether can encapsulate a set of own bootstrap component storehouse. Plus see MVC razor syntax inside directly through the background to output the front-end control method, and then intend to imitate the HtmlHelper package a set of Bootstraphelper, today is just a beginning, about how to encapsulate their own HTML components, and then slowly improve.
First, uncover the "veil" of HtmlHelper
Often use the razor writing of the Garden Friends know, in the cshtml, we can through the background of the method output into the front-end HTML components, such as we casually read two examples:
After the output becomes HTML
The blogger's curiosity has come again, how does it do? The HTML object and the label () method are then transferred to the definition
This shows that the HTML object is an instance of the HtmlHelper type, and the Label () method is an extension of the HtmlHelper type, so it can be invoked directly through Html.label ().
Now that we want to encapsulate our own htmlhelper, we have to understand how the label () method is implemented, and our great reflector comes in handy. Let's reverse-compile the System.Web.MVC.dll to see. Find Labelextensions This class
After a series of turns to definitions, we find the final approach
Again, we find the method for the final definition of the textbox ()
Yo West, the original is tagbuilder this a small thing, let a person feel magical don't want to. So sometimes we need to dare to decompile, it may seem that the high level behind is actually very simple ~ ~
Second, Bootstraphelper component packaging preparation
1. Define Bootstraphelper
With the above foundation to prepare, the next is the concrete implementation, we created a new empty MVC project, add the following file.
The compilation found the following error
Move HtmlHelper to the definition found that it has two constructors, two, three parameters, respectively
So, our bootstraphelper also defines two constructors, so the code becomes this:
namespace Extensions {public class BootstrapHelper:System.Web.Mvc.HtmlHelper {
<summary>///Initializes a new instance of the Bootstraphelper class using the specified view context and view data container. </summary>///<param name= "ViewContext" > View context </param>///<param name= "Viewdatacontainer" &G t; View data container </param> public bootstraphelper (ViewContext viewcontext, Iviewdatacontainer viewdatacontainer): Base (V
Iewcontext, Viewdatacontainer) {}///<summary>///Initializes a new instance of the Bootstraphelper class with the specified view context, view data container, and route collection. </summary>///<param name= "ViewContext" > View context </param>///<param name= "Viewdatacontainer" &G t; View data container </param>///<param name= "RouteCollection" > Routing collection </param> public Bootstraphelper ( ViewContext ViewContext, Iviewdatacontainer Viewdatacontainer, RouteCollection routecollection): Base (ViewContext, VI Ewdatacontainer, RouteCollection) {}}}
This solves the problem by reusing the constructor of the parent class by subclasses. Compile through!
2. Define Labelextensions
Above we've studied HtmlHelper, in HtmlHelper, different HTML components define different extension (extensions), and below we use the simplest label label as an example to define the label label in our Bootstraphelper.
Similarly, in the Extensions folder we created a new file LabelExtensions.cs, which defines the extension of the label label, which basically implements the following:
namespace Extensions {public static class Labelextensions {///<summary>///returns the lab by using the name of the specified HTML helper and form field El tags///</summary>///<param name= "html" > Extension method instance </param>///<param name= "id" > Label id</par
am>///<param name= "Content" > label contents </param>///<param name= "CssClass" > tag class style </param> <param name= "htmlattributes" > tag extra attributes (if the attribute contains "-", please use "_" instead) </param>///<returns> The HTML string </returns> public static mvchtmlstring label for the label label (this bootstraphelper HTML, string ID, string content,
String CssClass, Object htmlattributes) {//define tag name Tagbuilder tag = new Tagbuilder ("label"); Add additional attributes to the label idictionary<string, object> attributes = Bootstraphelper.anonymousobjecttohtmlattributes (
Htmlattributes); if (!string. IsNullOrEmpty (ID)) {attributes.
ADD ("id", id); } if (!string. IsNullOrEmpty (CssClass)) {//Add style tag to the label.
addCssClass (CssClass); }//ToTag adds text to the tag.
Setinnertext (content); Tag.
addCssClass ("Control-label"); Tag.
Mergeattributes (attributes); return Mvchtmlstring.create (tag.
ToString ()); }
}
}
Let's just define one method, and the other overloads are well extended, and here we add the "Control-label" style to all the label tags in the bootstraphelper, and of course, if the label label inside your project defines its own style, Then change it to the style you need. The above code compares the foundation, here does not explain each.
3. Define Bootstrapwebviewpage
The above definition of bootstraphelper and labelextensions, the preparation is done, but there is less an object, such as we in the cshtml page @html.label ("name") to write, An HTML variable is an object of a htmlhelper type, so if we need to use something like @bootstrap.label (), and so on, the Bootstrap variable should also be an object of bootstraphelper type. So if we're going to use this, we have to first define a bootstrap variable, where exactly is the variable defined. So bloggers think, where are the HTML variables defined? Go To Definition again
It turns out to be a subclass of this class of webviewpage, and again, we create a webviewpage subclass Bootstrapwebviewpage in the Extensions folder, and the implementation code is as follows:
Namespace Extensions
{public
abstract class bootstrapwebviewpage<t>: System.web.mvc.webviewpage<t >
{
//the variable public
bootstraphelper Bootstrap {get;}
used in the cshtml page <summary>
///Initialization Bootstrap object
///</summary> public
override void Inithelpers ()
{
base. Inithelpers ();
Bootstrap = new Bootstraphelper (ViewContext, this);
}
public override void Execute ()
{
//throw new notimplementedexception ();
}
}
}
As for the generics here, we'll do the explanation later.
4. Practice
With the above three steps, all the necessary methods and variables are complete, seemingly already "everything is only owed Dongfeng", is it so? Let's have a try.
Compile, index.cshtml the page is turned off, and finds that the Bootstrap object is still not found
What's going on, HTML can be found, that bootstrap variable go where ...
After a search of information, Found in the View folder there is a Web.config file (has not cared much about this thing before, now think of the inside is still learned OH), there is a node System.web.webPages.razor under a Pages node, the default is this:
<system.web.webPages.razor>
We change the pagebasetype of the pages node to our Webviewpage
<system.web.webPages.razor>
Then compile and reopen the index.cshtml.
OK, you can find the Bootstrap object. We will write the following index.cshtml inside:
@{
Layout = null;
}
<! DOCTYPE html>
Run a look at the effect:
How is it still an error? This problem should not be difficult to understand, because there is also the concept of namespaces in Razor using the @ Call back variables and methods, where does this namespace refer to? Or in the Web.config inside the view folder, where there are namespace nodes underneath the System.web.webPages.razor node, we add the namespace of the custom label () extension method. So the configuration becomes this:
<system.web.webPages.razor>
Run again
Third, bootstraphelper components to improve
Through a series of discovery pits, landfills experience, a most simple bootstraphelper component has been basically available. We will labelextensions simple and perfect under:
namespace Extensions {public static class Labelextensions {public static mvchtmlstring Label (This bootstraphelper h
TML, string id) {return Label (HTML, ID, NULL, NULL, NULL); public static mvchtmlstring Label (this bootstraphelper HTML, string content) {return Label (HTML, NULL, content,
NULL, NULL); public static mvchtmlstring Label (this bootstraphelper HTML, string ID, string content) {return Label (HTML, ID,
Content, NULL, NULL);
public static mvchtmlstring Label (this bootstraphelper HTML, string ID, string content, Object Htmlattributes) {
return Label (HTML, ID, content, NULL, htmlattributes); ///<summary>///Returns the label label///</summary>///<param name= html > Extension by using the specified HTML helper and the name of the form field
Law instance </param>///<param name= "id" > Label id</param>///<param "Content" > label contents </param> <param name= "CssClass" > tag class style </param>///<param name= "htmlattributes" > tag ExtraProperty (If the property contains "-", use "_" instead) </param>///<returns>label Tag HTML string </returns> public static Mvchtmlstring Label (this bootstraphelper HTML, string ID, string content, String CssClass, Object htmlattributes) {/
/defines the name of the tag tagbuilder tag = new Tagbuilder ("label"); Add additional attributes to the label idictionary<string, object> attributes = Bootstraphelper.anonymousobjecttohtmlattributes (
Htmlattributes); if (!string. IsNullOrEmpty (ID)) {attributes.
ADD ("id", id); } if (!string. IsNullOrEmpty (CssClass)) {//Add style tag to the label.
addCssClass (CssClass); }//Add text tag to the label.
Setinnertext (content); Tag.
addCssClass ("Control-label"); Tag.
Mergeattributes (attributes); return Mvchtmlstring.create (tag.
ToString ()); }
}
}
Oh, is not there is a kind of mold ~ ~ may have someone to say Bo main "cottage", hehe, regardless of the cottage does not cottage, you feel cool on the line.
Iv. Summary
This first came here, all the way landfills, the basic function is finally available. There are some need to improve the place, such as generics, such as Lamada expression, etc., more days, bloggers have time to improve. There are some of the most basic forms of control, we all need encapsulation, this estimate still a little work, only slowly to improve, and so on a certain degree of improvement will open source in git, I hope I can stick to it! If you think this article is helpful to you, please help recommend, your recommendation is the Master Bo insist on perfect power.
The above is small set to introduce the C # package HtmlHelper components Bootstraphelper, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!