There are different ways to access data from views to controller, In this post, we are going to learn how to access view form data into controller using Request
object. To demonstrate this, let’s create a form.
View Code
<h2>Receive With Request Form</h2> @using (Html.BeginForm("ReceiveWithRequestFormData", "ControllerAndAction")) { <ol> <li> @Html.Label("Username") @Html.TextBox("txtUserName") : user </li> <li> @Html.Label("Password") @Html.TextBox("txtPassword") : pass </li> </ol> <input type="submit" value="Login" /> } <div id="divResult"></div>
In the above code, we are creating two textboxes and a Login button. As the first parameter of the Html.BeginForm is ReceiveWithRequestForm
and second parameter is ControllerAndAction
so clicking on the Login button submit the page on /ControllerAndAction/ReceiveWithRequestForm
url.
Controller Code
public ActionResult ReceiveWithRequestForm() { return View(); }
Above method renders above View. When Login button is clicked below action method of the controller executes.
[HttpPost]
public ActionResult ReceiveWithRequestFormData()
{
string userName = Request.Form["txtUserName"]; string password = Request.Form["txtPassword"];
if (userName.Equals("user", StringComparison.CurrentCultureIgnoreCase)
&& password.Equals("pass", StringComparison.CurrentCultureIgnoreCase))
{
return Content("Login successful !");
}
else
{
return Content("Login failed !");
}
}
To access the form elements value, we can use Request.Form
collection by passing the name of the form element.