Creating Form Using HTML Helpers in ASP.NET Core MVC

Creating Form Using HTML Helpers in ASP.NET Core MVC

In this article, I will discuss Creating Form Using HTML Helpers in ASP.NET Core MVC Applications with an Example. Please read our previous article discussing Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications with Examples.

Creating Form Using HTML Helpers in ASP.NET Core MVC

Creating forms in ASP.NET Core MVC with HTML Helpers simplifies the process of generating HTML elements tied to the data model properties. HTML Helpers are server-side methods that return HTML strings that are then rendered in the browser. This approach allows for clean, maintainable, and reusable code. Here’s a step-by-step guide to creating a form using HTML Helpers in an ASP.NET Core MVC application.

Create a Model

First, define a model class that represents the data you want to collect in the form. For example, consider a simple User Profile model. So, create a class file named UserProfile.cs under the Models folder and then copy and paste the following code:

using System.ComponentModel.DataAnnotations;
namespace HTML_HELPER.Models
{
    public class UserProfile
    {
        public int? Id { get; set; }
        [Required(ErrorMessage ="Name Field is Required")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Biography Field is Required")]
        public string Biography { get; set; }
        public string Gender { get; set; }
        public List<string> Skills { get; set; } = new List<string>();
        public bool NewsLetter { get; set; }
        public string Preference { get; set; }
        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }
    }
}
Create a Controller

Create a controller with actions to display and process the form. The controller will have two actions: one for displaying the form (HTTP GET) and another for processing the form input (HTTP POST). So, create an Empty MVC Controller named UserProfileController under the Controllers folder and copy and paste the following code.

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace HTML_HELPER.Controllers
{
    public class UserProfileController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            // You can populate this with data from a database in a real app.
            ViewBag.SkillsList = new SelectList(new List<string> { "C#", "JavaScript", "Python", "SQL Server", "AWS" });
            ViewBag.PreferenceList = new SelectList(new List<string> { "Email", "SMS", "Phone Call", "WhatsApp" });
            return View();
        }

        [HttpPost]
        public IActionResult Index(UserProfile userProfile)
        {
            if (ModelState.IsValid)
            {
                // Save userProfile to the database or process it further here
                // For demonstration, just redirect back to the form with a success message
                TempData["Success"] = "UserProfile submitted successfully!";
                return RedirectToAction("Index");
            }

            // If we got this far, something failed; redisplay form
            ViewBag.SkillsList = new SelectList(new List<string> { "C#", "JavaScript", "Python", "SQL Server", "AWS" });
            ViewBag.PreferenceList = new SelectList(new List<string> { "Email", "SMS", "Phone Call", "WhatsApp" });
            return View(userProfile);
        }
    }
}

Create a View

Create a view (Index.cshtml) for the Index action in the UserProfileController. Use HTML Helpers to create form fields bound to the model properties. Add a new Razor view Index.cshtml under the Views/UserProfile directory, and then please copy and paste the following code. To make the HTML form responsive, we are using Bootstrap and applying its grid system and form control classes to our elements.

@model HTML_HELPER.Models.UserProfile

@{
    ViewBag.Title = "User Profile Form";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>User Profile Form</h2>

@using (Html.BeginForm("Index", "UserProfile", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.LabelFor(model => model.Name)
            @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.LabelFor(model => model.Biography)
            @Html.TextAreaFor(model => model.Biography, new { @class = "form-control", rows = 3 })
            @Html.ValidationMessageFor(model => model.Biography, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="form-check form-check-inline">
            @Html.RadioButtonFor(model => model.Gender, "Male", new { @class = "form-check-input" })
            @Html.LabelFor(model => model.Gender, "Male", new { @class = "form-check-label" })
        </div>
        <div class="form-check form-check-inline">
            @Html.RadioButtonFor(model => model.Gender, "Female", new { @class = "form-check-input" })
            @Html.LabelFor(model => model.Gender, "Female", new { @class = "form-check-label" })
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.LabelFor(model => model.Skills)
            @Html.ListBoxFor(model => model.Skills, (SelectList)ViewBag.SkillsList, new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.NewsLetter)
        <div class="form-check">
            @Html.CheckBoxFor(model => model.NewsLetter, new { @class = "form-check-input" })
            @Html.LabelFor(model => model.NewsLetter, "", new { @class = "form-check-label" })
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.LabelFor(model => model.Preference)
            @Html.DropDownListFor(model => model.Preference, (SelectList)ViewBag.PreferenceList, "Please Select", new { @class = "form-control" })
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.LabelFor(model => model.Password)
            @Html.PasswordFor(model => model.Password, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-6 mb-3">
            @Html.HiddenFor(model => model.Id)
        </div>
    </div>

    <button class="btn btn-primary" type="submit">Submit</button>
}

@if (TempData["Success"] != null)
{
    <div>@TempData["Success"]</div>
}
Using HTML Helpers
  • BeginForm: Starts the form using the specified action method.
  • TextBoxFor: Renders an input of type text for a specified model property.
  • TextAreaFor: Renders a textarea for a specified model property.
  • DropDownListFor: This function renders a select list (dropdown) for a specified model property using a provided list of values.
  • RadioButtonFor: Renders a radio button for a specified model property.
  • CheckBoxFor: Renders a checkbox for a specified model property.
  • ListBoxFor: Renders a list box for a specified model property.
  • HiddenFor: Renders a hidden input for a specified model property, useful for storing IDs that are not changed by the user.
  • PasswordFor: Renders an input of type password for a specified model property.
How It Works
  • GET Request: When a user navigates to the /UserProfile/Index, the Index action method with [HttpGet] is invoked, which displays the form to the user.
  • POST Request: Upon form submission, the browser sends a POST request to the server, hitting the Index action method with [HttpPost]. The method attempts to save the data and, upon success, redirects to the same Index action method, which displays the message from the TempData. If an error occurs, then it will display the error message.
Key Points of Bootstrap:
  • Form and Grid: The form uses the Bootstrap grid system (form-row and col-md-6 mb-3) to organize the form fields. This ensures that the layout is responsive and adapts to different screen sizes.
  • Form Controls: Form elements are styled with Bootstrap’s form-control class for a unified and attractive appearance.
  • Buttons: The submit button uses the btn btn-primary class for styling consistent with the Bootstrap theme.
Running the Application

When you run the application and navigate to /UserProfile/index, you’ll see the UserProfile form, as shown below.

Creating Forms Using HTML Helpers in ASP.NET Core MVC Applications with an Example

Submitting the form with valid data should display a success message, indicating that the POST action in the UserProfileController processed the form submission.

In the next article, I will discuss Generating Links in ASP.NET Core MVC Applications with Examples. In this article, I explain how to create forms using HTML helpers in ASP.NET Core MVC applications with an example. I hope you enjoy this “Creating Forms Using HTML Helpers in ASP.NET Core MVC” article.

Leave a Reply

Your email address will not be published. Required fields are marked *