How to use html.textbox in MVC

Home > Search > How-to
  by

In it's most basic form, an HTML textbox in MVC will contain the following. In this example, the GET method is used and the form points to www.example.com/Example/Index.

@using (Html.BeginForm("Index", "Example", FormMethod.Get))
{
  @Html.TextBox("box1")
}

 

This will produce nothing more than an empty, simple textbox. 

 

The browser will contain the following HTML.

<input id="box1" name="box1" type="text" value>

 


 

PLACEHOLDER

We typically want to enter null in the second field. If you add text to the second field, this will become the default value for the textbox. The default value will not clear when clicking in the textbox. Notice the HTML ends with value. This means value has not been set, which is typically what you want.

It is common to add a placeholder.

@using (Html.BeginForm("Index", "Example", FormMethod.Get))
{
  @Html.TextBox("box1", null, new { @placeholder="search . . ." })
}

 

This will produce a textbox with placeholder text. 

 

The browser will contain the following HTML.

<input id="box1" name="box1" placeholder="search . . ." type="text" value>

 


STYLING

@class = "my-textbox" can be added to style the textbox. 

@using (Html.BeginForm("Index", "Example", FormMethod.Get))
{
  @Html.TextBox("box1", null, new { @class = "my-textbox", @placeholder="search . . ." })
}

 

Following is CSS that you can use for my-textbox.

.my-textbox {
  display: inline-block;
  float: none;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555555;
  vertical-align: middle;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
          transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}

 

This will produce the following textbox.

 

The browser will contain the following HTML.

<input class="my-textbox" id="box1" name="box1" placeholder="search . . ." type="text" value>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments