[Translation] use custom ViewHelper to simplify Asp.net MVC view development-part2

Source: Internet
Author: User

Next article... First, let's see how to create a textbox we discussed earlier

We already know that the textbox to be created has a text value corresponding to it:

  1. Text Value in label
  2. The optional values are placed in Textbox.
  3. Optional verification message)

If the above three conditions can be met, we can certainly meet the five conditions in part1. in addition, you can specify whether the textbox is enclosed in the li label and whether the textbox is in readonly mode through attributes. in this way, we can better reuse the code in the view page. The following code contains all attributes of the HtmlText object (inherited by: AbstractHtmlViewObject, in the class diagram of part1:

private readonly string mLabelText; private readonly bool mCreateLabel; private readonly object mValue; private readonly string mValidationMessage; private readonly bool mCreateValidationMessage; private readonly bool mCreateLi; private readonly bool mReadonly;  public HtmlText(     ViewRequestContext requestContext, string name, string labelText, objec    string validationMessage, bool @readonly, bool createLi, object attribu    : base(requestContext, name) {     mLabelText = labelText;     mCreateLabel = !string.IsNullOrEmpty(mLabelText);     mValidationMessage = validationMessage;     mCreateValidationMessage = !string.IsNullOrEmpty(validationMessage);     mCreateLi = createLi;     mReadonly = @readonly;     Attributes = attributes;      object valueToAssign = value;     if (valueToAssign == null)     {         // see if the ModelState has a value for this         valueToAssign = GetModelStateValue(name, typeof(string));     }      mValue = valueToAssign; } 

In the constructor, we store a series of private variables and initialize a bool type that will be used in the StartView method. In addition, you can find that the GetModelStateValue method is used here. so far, we have not discussed this method much. This method will be mentioned later. Before passing in parameters to the constructor, we noticed that:

  1. The value parameter is of the object type.
  2. The attributes parameter of the object type is passed in.

The Value parameter is defined as the object type because it makes it easier for users to use and is consistent with the execution method of ASP. Net MVC Helpers. The attributes parameter can be called to expand the generated HTML. For example, if you want to set the maxlength attribute of textbox to 5, you only need to input the anonymous type "new {maxlength = 5}". the input tag converts the anonymous type to the HTML attribute maxlength = 5. this also complies with the existing extension methods of HTML Helper in Asp.net MVC. every View helper object should support this behavior for greater flexibility. the remaining two methods in this class are the StartView and EndView methods inherited from the parent class.

StartView and EndView are defined as follows:

public override void StartView() {     HttpResponseBase httpResponse = RequestContext.HttpResponse;      TagBuilder htmlLiTagBuilder = new TagBuilder("li");     if (mCreateLi)     {         httpResponse.Write(htmlLiTagBuilder.ToString(TagRenderMode.StartTag));     }      // write out label if provided     if (mCreateLabel)     {         TagBuilder labelTag = new TagBuilder("label");         labelTag.Attributes.Add("for", Name);         labelTag.SetInnerText(mLabelText);         httpResponse.Write(labelTag.ToString(TagRenderMode.Normal));     }      string stringValue = string.Empty;     if (this.mValue != null)     {         stringValue = Convert.ToString(this.mValue, CultureInfo.CurrentCulture);     }      if (this.mReadonly)     {         TagBuilder textTag = new TagBuilder("span");                 textTag.AddCssClass("readonly-text");         textTag.SetInnerText(             Convert.ToString(this.mValue, CultureInfo.CurrentCulture));         httpResponse.Write(textTag.ToString(TagRenderMode.Normal));     }     else     {         // Use MVC helpers to create the actual text box         httpResponse.Write(RequestContext.HtmlHelper.TextBox(             Name, this.mValue, Attributes));     }      if (this.mCreateLi)     {         httpResponse.Write(htmlLiTagBuilder.ToString(TagRenderMode.EndTag));     } } public override void EndView() {     // Not needed for this element } 

There are many notable points in the StartView method. Let's discuss them one by one. First, we use System. Web. Mvc. TagBuilder to generate HTML, rather than directly writing HTML tags. TagBuilder can only be used in Asp.net MVC. I recommend that you use TagBuilder instead of HTML tags in HTML generation. The following is a class diagram of TagBuilder:

The following table describes some methods in TagBuilder:

Name Description
AddCssClass The name of the class added to css. If the class already exists, the added class will take effect with the original class.
MergeAttribute This method is used to add or update tag attributes. This method has an overload that accepts the replaceExisting parameter. By default, defined attributes are not overloaded.
MergeAttributes Same as above, but all attributes can be added or updated in a method.
SetInnerText Set text in tags
ToString Is overloaded. Generate the corresponding html code. The TagRenderMode Enumeration type controls how to generate HTML tags.

 

In the ToString line in the table above, the TagRenderMode enumeration is used to control the way TagBuilder generates HTML tags. The TagRenderModel is as follows:

TagRenderModel Result example
Normal <Div name = "Sample01"> Some content here </div>
StartTag <Div name = "Sample01">
EndTag </Div>
SelfClosing <Div name = "Sample01"/>
   

 

Based on the HTML tag you want to create and how you use it, you will find that using the TagRenderModel can create any HTML tag you want to create. in the StartView method mentioned above, you will find that the TagRenderModel is set to StartTag, Normal, EndTag, and other different types based on different conditions. if you assign a value to the InnerHTML attribute and use StartTag and EndTag to generate it, you must remember that InnerHtml will not be automatically generated. You must also explicitly use the InnerHtml attribute itself. Next we will discuss how to create the HtmlHelper extension method.

-------------------------------------------

To be continued...

Http://mvcviewhelpers.codeplex.com/

Translated by CareySon

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.