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.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...