Chapter 5.  Creating MVC Bootstrap Helper and Tag Helpers

ASP.NET Core allows developers to create their own HTML Helper methods either by creating static or extension methods. In essence, an HTML Helper is simply a method that returns an HTML string.

HTML Helpers enable you to use the same common block of markup on multiple pages and make the code and markup in your pages easier to read and maintain. This promotes the use of reusable code, and developers can also unit test their helper methods.

ASP.NET Core also introduced a new concept called a Tag Helper that serves a similar purpose to a HTML Helper. The Tag Helpers is not a replacement for the traditional the HTML Helpers but provides developers with an alternative way to generate cleaner HTML markup.

In this chapter, we will cover the following topics:

  • An overview of the built-in ASP.NET Core HTML and Tag Helpers
  • Creating HTML Helpers using static methods
  • Creating HTML Helper using extension methods
  • Creating self-closing helpers
  • Creating Tag Helpers

Built-in HTML Helpers

An HtmlHelper is a method that renders HTML content inside a view. It is intended to allow developers to reuse a common block of HTML markup across multiple pages.

ASP.NET MVC provides a range of standard, out-of-the-box HTML Helpers. For example, to produce the HTML for a textbox with an ID and name attribute of CustomerName, use the following code:

<input type="text" name="CustomerName" id="CustomerName"> 

You should use the TextBox helper as illustrated:

@Html.TextBox("CustomerName") 

The majority of the built-in HTML Helpers offer several overloaded versions. For instance, to create a textbox and explicitly set its name and value attributes, you should use the following overloaded TextBox helper method:

@Html.TextBox("CustomerName"","Northwind Traders") 

Most built-in helpers also offer the option to specify HTML attributes for the element that is generated by passing in an anonymous type. In the following example, we'll create a textbox and set its style property using one of the overload methods:

@Html.TextBox("CustomerName","Northwind Traders", new { style="background-color:Blue;" }) 

Tip

You can read more about the standard HTML Helpers available in ASP.NET MVC from http://bit.ly/MVCFormHelpers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.24.106