In this article I will explain with an example, how to set Id to HTML.TextBoxFor Helper method in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Model

The Model class consists of following properties.
public class PersonModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
 

Controller

The Controller consists of following Action method.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
 
 

View

HTML Markup

Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of a TextBox created using Html.TextBoxFor Html Helper method.
The TextBox contains following parameters:
expression – An expression that identifies the object that contains the properties to render.
htmlAttributes – An object that contains the HTML attributes to set for the element. In this case it is Id.
@model HTML_TextBoxFor_Id_MVC.Models.PersonModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.TextBoxFor(m => m.Name, new { @id = "txtName" })
</body>
</html>
 
 

Screenshot

Rendered Page

Set Id to Html.TextBoxFor Helper Method in ASP.Net MVC
 
 

Downloads