Form Collection in MVC


What is Form Collection in MVC

In this article I will explain how to fetch data from controls which are on View to Controller. There are many ways to fetch these values and Form Collection is the one of them.
Action is the element of Form Tag and it is used to redirect page when we submit the button.
In my one of last article I explained the GET and POST method . And in POST method I showed that data stored in FORM if Method set as POST. I also explained that data stored using the controls property Name.
Note: - if you are not aware the concept of GET and POST in MVC then kindly Click Here.
As we know that if our method set as POST then all data stored in Form so we can access this data on our controller using FormCollection.

Example of Form Collection

In this example I have created the Home Controller and in this I have created index view.
In this view I have created the following form in which I am taking first name and last name from the user. For each control I have set the property name. This property I will use in form collection to fetch the data.

Code of Index.cshtml

  
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" action="Welcome\Index">
        <table>
            <tr>
                <td>Enter First Name</td>
                <td><input type="text" id="fname_id" name="fname_name" /></td>
            </tr>
             <tr>
                <td>Enter Last Name</td>
                <td><input type="text" id="lname_id" name="lname_name" /></td>
            </tr>
             <tr>
                <td></td>
                <td><input type="submit"  /></td>
            </tr>
        </table>
    </form>
</body>
</html>
    
In action I have set the welcome controller and index view. So I have created welcome controller and create index view.
In index view method I have passed FormCollection object as parameter. And using this we can fetch the data.

Code of Home Controller

  
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class WelcomeController : Controller
    {
        

        public ActionResult Index(FormCollection data)
        {
            string fname = data["fname_name"];
            string lname = data["lname_name"];
            Response.Write("Your Full name is= " + fname + " " + lname);


            return View();
        }

    }
}
    
Now execute this code


You will get following output


No comments:

Post a Comment