Asp.Net Core MVC: Textbox and TextboxFor Controls

How to use TextBox and TextBoxFor control in asp.net core mvc application. Difference between these two types of controls and features.
In today's article I will show a simple tutorial with example what is difference between TextBox and TextBoxFor control and its uses and value retravel at controller end on post in asp.net core mvc application. Here I am using asp.net core 8 mvc. So first we will understand the difference between TextBox and TextBoxFor.

Key Difference Between TextBox and TextBoxFor

Key Difference Between TextBox and TextBoxFor

Features of TextBox

TextBox  is an html helper to render the textbox input control to your view. It is loosely coupled. TextBox control accepts only string type of name and value as parameter. This is used when we don't have any model class. In view we will define it as @Html.TextBox.

@Html.TextBox("Control Name", "Default Value", new { @class = "Css Class Name" })

Example TextBox

View Code:
@using (Html.BeginForm("Ind", "", FormMethod.Post))
{
    @Html.TextBox("EmployeeName", "", new { @class = "Css Class Name" })
    <br /><br />
    <input type="submit" value="Submit" />
} 
Controller Code:
[HttpPost]
public IActionResult Index(string EmployeeName)
{
    return View();
} 
Here we have passed name of TextBox control as parameter in HttpPost method. Now run the code to check the output.
TextBox control
Ones you click on Submit break point at controller end will execute, and here we will be able to get the entered value in TextBox control.

Controller Value

To get the TextBox control value at controller end name of parameer passed at controller action method and TextBox control name must be same.

Features of TextBoxFor

TextBoxFor  is an html helper to render the textbox input control to your view. It is strongly type. It uses model class property. TextBoxFor control uses strongly type view to bind the mode class property. In view we will define it as @Html.TextBoxFor.

@Html.TextBoxFor(Model Property, new { @class = "Css Class Name" })

Example TextBoxFor

View Code:
@model UserModel
@{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.Name, new { @class = "" })
    @Html.TextBoxFor(m => m.Address, new { @class = "" })
    <br />
    <input type="submit" value="Submit" />
} 
Controller Code:
[HttpPost]
public IActionResult Index(UserModel userModel)
{
    return View();
} 
Here in above code, I have used TextBoxFor to define the textbox input control and bind it with model class property. In controller I have passed the model class as a parameter and to get the value on click of submit button in controller. 

TextBoxFor control
As we click on submit button, we will be able to get the value at controller end in model class property passed as parameter. 

Model class value

Post a Comment