In this article we are going to discuss about the different way of getting the value from the textbox usingย MVC razor.

Index.cshtml

Here we had included the Html.TextBox in the Index.cshtml.

<div>
@using (Html.BeginForm(“Index”, “Index”, FormMethod.Post))
{
@Html.Label(“Enter Your Name”)
@Html.TextBox(“txtName“)
<input type=”submit” id=”btnSubmit” name=”Submit” />
}
@ViewBag.Name
</div>

Method 1: Using the Name(id) of the @Html.TextBox

IndexController :

We having a Index action method for getting the textbox value from the view.

public ActionResult Index(string txtName)
{
ViewBag.Name = txtName;
return View();
}

  • In this method we can get the value of textboxย  using id/name. ie., txtName.
  • Getting value type must be string, else it will show the following error ( if we change type to int)

Method 2: Using the FormCollection

FormCollection does not contain key/value pairs, just having an id/name. Using the name/id of the text box we can get the value as shown below..

public ActionResult Index(FormCollection Form)
{
ViewBag.Name = Form[“txtName”];
return View();
}

Below image shows quick view of formcollection

 

Keep cool coding….