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

Source: Internet
Author: User

Next article... Now let's start to discuss how to create the HtmlHelper extension method.

We have discussed all aspects of creating the HtmlText class. Include the extension methods created for HtmlText. These extension methods include those called directly by View. The following code demonstrates several different constructors of HtmlText:

public static class HtmlHelperExtensions {     #region Textbox     public static IViewObject NewText(         this HtmlHelper htmlHelper, string name)     {         return NewText(htmlHelper, name, null);     }          public static IViewObject NewText(         this HtmlHelper htmlHelper, string name, string labelText)     {         return NewText(htmlHelper, name, labelText, null);     }          public static IViewObject NewText(         this HtmlHelper htmlHelper, string name, string labelText, object value)     {         return NewText(htmlHelper, name, labelText, value, null, false, true, null);     }      public static IViewObject NewText(         this HtmlHelper htmlHelper, string name, string labelText, object value,          string validationMessage, bool @readonly, bool createLi, object attributes)     {         IViewObject viewObject = new HtmlText(             new ViewRequestContext(htmlHelper), name, labelText, value,              validationMessage, @readonly, createLi, attributes);         viewObject.StartView();         return viewObject;     }     #endregion      //NOTE: SOME CONTENT OMITTED FROM THIS SNIPPET } 

The NewText method has four different versions of overload, all of which belong to the System. web. mvc. the Extension Method of HtmlHelper, only the last method is used to really work, and other methods are encapsulated to make it easier for users to use. in the above Code, the HtmlText object is initialized by passing in appropriate parameters, and the view is initialized through the StartView method, the HtmlText called in StartView will return a suitable object to dynamically inject Html into the View. now let's take a look at how to use these methods in the view.

We have created an HtmlText object that can be used in the View. Now we can use it. As mentioned above, if you want to create a textbox to meet the Ricky standard, you must write the following code:

<li>     <label for="FirstName">First name</label>     <%= Html.TextBox("FirstName") %>     <%= Html.ValidationMessage("FirstName", "*") %> </li> 

Now, by using HtmlHelper, we can simplify the Code as follows:

<% Html.NewText("FirstName", "First name"); %> 

The Html generated by the above two methods is exactly the same, and we have achieved the previously set goal. From now on, we can use this Helper to simplify the development of Asp.net MVC view. The EndView method is not used in the code above. Next we will study a more complex HTML construction-radio button to see how it is implemented.

Use Asp.net MVC to create a set of radio buttons. The code is generally as follows:

<li>     <div class="option-group" id="GenderContainer">         <label for="Gender">Gender</label>         <% foreach (SelectListItem item in Model.GenderList)            { %>                 <%= Html.RadioButton(item.Text, item.Value)%>                 <span><%= item.Text%></span>         <% } %>     </div> </li> 

The code above is excerpted from AddContactClass. aspx view. All code can be downloaded from the website of this article. In the code above, ContactController uses the Model. GenderList attribute to return code in a centralized manner:

public ActionResult AddContactClassic() {     AddContactModel addModel = InternalGetInitialAddModel();      return View(addModel); }  private AddContactModel InternalGetInitialAddModel() {     string maleString = Gender.Male.ToString();     string femaleString = Gender.Female.ToString();      IList<SelectListItem> genderRadioButtons = new List<SelectListItem>()     {         new SelectListItem { Text = maleString, Value = maleString },         new SelectListItem { Text = femaleString, Value = femaleString }     };      AddContactModel model = new AddContactModel { GenderList = genderRadioButtons };      return model; } 

The generated HTML is as follows:

In the code for creating a radio button above, there are many attempts to conceal the true intent of the elements (for example, why do we write HTML to meet the Ricky standard ?) For example, the div of the outer layer and the span of the inner layer wrap the text for label. if we only need to declare a set of radio buttons and specify related values, isn't it better? Next we will create HtmlRadioButtonGroup view helper, which can meet the requirement that we can only declare and specify relevant values to create the corresponding html. Using HtmlRadioButtonGroup, we can streamline the previous radio button as follows:

<% Html.NewRadioButtonGroup("Gender", Model.GenderList); %> 

In the above code, we can create Html from a higher perspective. The purpose of this Code is clear, rather than focusing on the details of Html. The following code creates a helper for generating HTML for us, that is, the HtmlRadioButtonGroup class. The following code shows the unique constructor and Its fields of this class:

private readonly List<SelectListItem> mSelectList; private readonly bool mCreateLi;  public HtmlRadioButtonGroup(     ViewRequestContext requestContext, string name,      IEnumerable<SelectListItem> selectList, bool createLi, object attributes)     : base(requestContext, name) {     mSelectList = new List<SelectListItem>();     if (selectList != null)     {         mSelectList.AddRange(selectList);     }      mCreateLi = createLi;     Attributes = attributes; }

Does it look like the constructor of our previous HtmlText object? Its constructor makes RequestContext available by passing parameters. The constructor initializes all fields, which means that this class is passed in the StartView method (the translator presses: Because the RequestContext method can be passed in StartView, the following code is the full version of StartView:

public override void StartView() {     HttpResponseBase httpResponse = RequestContext.HttpResponse;      TagBuilder liTagBuilder = new TagBuilder("li");     if (mCreateLi)     {         httpResponse.Write(liTagBuilder.ToString(TagRenderMode.StartTag));     }      TagBuilder divTag = new TagBuilder("div");     divTag.AddCssClass("option-group");     divTag.MergeAttribute("name", Name);     if (Attributes != null)     {         divTag.MergeAttributes(new RouteValueDictionary(Attributes));     }      TagBuilder labelTag = new TagBuilder("label");     labelTag.MergeAttribute("for", Name);     labelTag.SetInnerText(Name);     httpResponse.Write(labelTag.ToString(TagRenderMode.Normal));      httpResponse.Write(divTag.ToString(TagRenderMode.StartTag));      // Write out the radio buttons, let the MVC Helper do the hard work here     foreach (SelectListItem item in this.mSelectList)     {         string text = !string.IsNullOrEmpty(item.Text)                         ? item.Text                         : item.Value;          httpResponse.Write(RequestContext.HtmlHelper.RadioButton(             Name, item.Value, item.Selected));          // Note: Because we are using HtmlHelper.RadioButton the <input>          //       elements will have duplicate ids         //       See: http://forums.asp.net/t/1363177.aspx         //       In order to avoid this we could do this ourselves here         TagBuilder spanTag = new TagBuilder("span");         spanTag.SetInnerText(text);                 httpResponse.Write(spanTag.ToString(TagRenderMode.Normal));     }      httpResponse.Write(divTag.ToString(TagRenderMode.EndTag));      if (this.mCreateLi)     {         httpResponse.Write(liTagBuilder.ToString(TagRenderMode.EndTag));     } } 

Here, the idea and HtmlText class are removed from the first day, that is, all HTML code is generated in the StartView method. Therefore, the StartView method creates some HTML tags, traverses the elements in mSelectList, and generates a RadioButton for each element through the RadioButton extension method that comes with Asp.net MVC. It is best to override these methods when reusing these methods (the translator presses: Read the above Code comment ).

From the comments in the above code, we can see that HtmlHelper is used. there is an obvious bug in the RadioButton extension method, that is, the id and name use the same value, here, because the name attribute should have been set to the same for RadioButton, they can be logically connected into a group, but the id attribute is unique to each element, this method is not used to solve this bug here, but we will use this method first for the sake of simplicity. the two Html helper Objects Created above do not use the EndView method. You can already doubt why this method exists. In the following HtmlFieldSet Helper, I will show you the purpose of EndView.

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

To be continued...

Http://mvcviewhelpers.codeplex.com/

Translated by CareySon

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.