Generating HTML

As discussed in Chapter 1, Introduction to ASP.NET Core, browsers can understand only HTML, CSS, and JavaScript, irrespective of the technology that you use to build the web application. This holds true when building the application in ASP.NET MVC as well.

Most applications get the user input, process the input, and then store the required information in the database to retrieve them later. In the context of web applications, Form HTML elements are used to get the user input.

The following are a couple of ways to generate HTML elements in ASP.NET Core:

  • HTML Helpers
  • Tag Helpers

HTML Helpers are server-side methods that aid in generating HTML elements, which can be understood by the browsers. HTML helpers were the primary method of generating the HTML elements up till ASP.NET MVC 5.

Tag Helpers, introduced in ASP.NET Core, also produce HTML elements. Tag helpers, which we will discuss in a later section of this chapter, will look just like HTML elements where you add attributes to identify them as Tag Helpers. The advantage of using Tag helpers over HTML helpers is that the user interfaces designers/engineers do not need to worry about Razor code. They just code with HTML elements and additional attributes.

Before discussing HTML helpers and Tag helpers, let's take a step back and talk about why we need them in the first place.

Let's consider a simple form, as shown in the following picture, where we would like to get the user's name and their age. If the user enters her age, we will display You are eligible to vote!. If not, we will display You are not eligible to vote now:

Generating HTML

The following is the HTML code to show the preceding simple form:

<form>
  <table>
    <tr>
      <td>
        <label for="txtName">Name</label>
      </td>
      <td>
        <input type="text" id="txtName" />
      </td>
    </tr>
   <tr>
     <td>
       <label for="txtAge">Age</label>
     </td>
     <td>
      <input type="text" id="txtAge" />
     </td>
   </tr>
   <tr>
     <td colspan="2">
       <input type="submit"  />
     </td>
   </tr>
  </table>
</form>

This method of coding HTML elements directly is time-consuming and error-prone. For example, in the preceding form, the label and input HTML elements refer to the same element (txtName in the first group and txtAge in the second group). If we hand-code the HTML element, there is a possibility of a typo error in building the HTML element.

HTML Helpers

HTML helpers are server-side methods that generate HTML for you. We can generate the same form using HTML helpers as follows (HTML.BeginForm, @Html.Label, and @Html.TextBox generate the HTML form element, label, and textbox elements, respectively):

@using (Html.BeginForm())
 {
   <table>        
     <tr> 
       <td>@Html.Label("Name")</td>
       <td>@Html.TextBox("txtName")</td>
     </tr>
     <tr>
       <td>@Html.Label("Age")</td>
       <td>@Html.TextBox("txtAge")</td>
     </tr>
     <tr>
       <td colspan="2"><input type="submit" value="Submit" /></td>
     </tr> 
   </table>
}

HTML Helpers

You might wonder why we need to use HTML helpers when we can write the HTML code manually. Things will get more complex when we pass the model from the Controller to the view. Using HTML helpers, we can directly build form elements from Models files so that they will pick the names from the Models that you are using.

For example, let's create a folder called Models and a class called Person. This class will act as a model as shown in the following screenshot:

HTML Helpers

The Person class is just a POCO (Plain Old C# Object) class and will act as a model. The complete code for this class is as follows:

public class Person
{
  public int PersonId { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
}

Let's create a new action method called ValidateAge. In this method, we will create an empty Person class and pass the Model to the View. We will also create a dynamic property called Title in ViewBag so that we can display this value in View:

[HttpGet]
public IActionResult ValidateAge()
{
  ViewBag.Title = "Validate Age for voting";
  Person person1 = new Person();
  return View(person1);
}

In the view, create the form using the following HTML Helpers:

@model Chapter4.Models.Person
@using (Html.BeginForm("ValidateAge", "Home", FormMethod.Post))
 {
   <table>
     <tr>
       <td>@Html.LabelFor(Model => Model.Name) </td>
       <td>@Html.TextBoxFor(Model => Model.Name) </td>
     </tr>
     <tr>
       <td>@Html.LabelFor(Model => Model.Age)</td>
       <td>@Html.TextBoxFor(Model => Model.Age)</td>
     </tr>
     <tr>
       <td colspan="2"><input type="submit" value="Submit" /></td>
     </tr>
   </table>
}

In the first line, we are telling the View that we are passing the Model of type Person class. This enables you to use the strong type of Model, that is, when you type Model and a dot, IntelliSense provides you with all the properties of the Person class

In the second line, we are using the overloaded BeginForm HTML helpers which accept three parameters—the action method name, the Controller name, and the Form method.

Simply, when the user submits the form, the information should be passed to the mentioned action of the Controller.

In the LabelFor and TextBox For HTML helpers, we are just passing Model properties (name and age); it automatically queries and gets the Model properties and builds the respective HTML elements. This is one of the primary advantages of using HTML helpers. Without using the HTML helpers, this process might become complex.

Now, let's write the respective POST action method in the same way. In the following POST action method, based on the age entered in the form, we set the dynamic property as Message.

[HttpPost]
public IActionResult ValidateAge(Person person1)
{
  if(person1.Age>=18)
  {
    ViewBag.Message = "You are eligible to Vote!";
  }
  else
  {
    ViewBag.Message = "Sorry.You are not old enough to vote!";
  }
  return View();
}

It is to be noted that both the GET and POST action method refer to the same View —ValidateAge.cshtml. Add the following content to the View just above the form element:

@if(ViewBag.Message!=null)
 {
   <b>@ViewBag.Message</b>
 }

Once the user submits the form, the POST action method sets the dynamic Message property in ViewBag. However, the value of this property will be null when the View is rendered as part of the GET request. If the value is not null, insert the message at the top of the page.

When you run the application, you'll get the following output:

HTML Helpers

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

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