ASP.NET MVC – Access form data into the controller using Request

Updated on     Kisan Patel

This tutorial will explain you how to access form data into controller using request in asp.net mvc with example.

We can get post requested data by the FormCollection object. The FormCollectionobject also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form.

string userName = Request.Form["txtUserName"];

For Example,

Index.cshtml

@{
ViewBag.Title = "Index";
}

<h2>Receive With Request Form</h2>
@using (Html.BeginForm("LoginWithRequestFormData", "Home"))
{
<table>
   <tr>
     <td>
       @Html.Label("Username")
     </td>
     <td>
       @Html.TextBox("txtUserName")
     </td>
   </tr>
   <tr>
     <td>
       @Html.Label("Password")
     </td>
     <td>
       @Html.TextBox("txtPassword")
     </td>
  </tr>
</table>
<input type="submit" value="Login" />
}

In the above code, we are adding two textboxes and a Login button.
HomeController.cs

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 LoginWithRequestFormData()
{
    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 !");
    }
}

You can also access the form element in the action method of the controller is by using FormCollection.

For Example,

[HttpPost]
public ActionResult LoginWithRequestFormData(FormCollection form)
{
    string userName = form["txtUserName"];
    string password = form["txtPassword"];
    if (userName.Equals("user", StringComparison.CurrentCultureIgnoreCase)
    && password.Equals("pass", StringComparison.CurrentCultureIgnoreCase))
    {
        return Content("Login successful !");
    }
    else
    {
        return Content("Login failed !");
    }
}

In the above, all the form elements comes as FormCollection and we can access them using element’s name.

Request-Form-Demo

Download Code From Here


ASP.NET MVC

Leave a Reply