Different way of getting @Html.TextBox value from controller

Let we discuss about the different way of getting the value of textbox in MVC razor

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>

IndexController :

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

  • 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 ( change the int)

@Html.textbox2

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

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..

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

Below image show quick view of formcollection


@Html.textbox1

Advertisements
By Sriramjithendra Posted in ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s