ASP.NET MVC > Controller

Access form data into controller using FormCollection in ASP.NET MVC

How to access form data into the controller using FormCollection?


The other ways to access the form element in action method of the controller is by using FormCollection.

VIEW PAGE
<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>
CONTROLLER CODE
   [HttpPost]
        public ActionResult ReceiveWithRequestFormCollection(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 this case, all the form elements comes to this method as FormCollection and we can access them using element’s name.

 Views: 4706 | Post Order: 46



Write for us