DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Edited on

Form Collection in Asp.net with View Examples

  1. Create a new ASP.NET MVC project in Visual Studio.

  2. In the HomeController, add an action method to handle the form submission:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SubmitForm(FormCollection form)
    {
        // Access form values using the FormCollection
        string name = form["Name"];
        string email = form["Email"];

        // Do something with the form values

        return View("Result");
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. In the Views folder, create a new folder called Home and add a new view file called Index.cshtml inside it. Update the view file with the following code:
@{
    ViewBag.Title = "Form Collection Example";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Form Collection Example</title>
</head>
<body>
    <h2>Submit Form</h2>
    @using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
    {
        <div>
            <label>Name:</label>
            <input type="text" name="Name" />
        </div>
        <div>
            <label>Email:</label>
            <input type="email" name="Email" />
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    }
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Create another view file called Result.cshtml inside the Home folder. Update the view file with the following code:
@{
    ViewBag.Title = "Form Submitted";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Form Submitted</title>
</head>
<body>
    <h2>Form Submitted Successfully</h2>
    <p>Name: @ViewBag.Name</p>
    <p>Email: @ViewBag.Email</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, the Index action method renders the Index.cshtml view, which contains a form with two input fields for name and email. When the form is submitted, the SubmitForm action method is called, and the form values are captured using the FormCollection object. You can access individual form values using their names as keys in the form collection.

After processing the form values, the action method returns the Result view, passing the values through ViewBag for display.

Note: Using the FormCollection object directly is not the recommended approach for form processing. It's better to use model binding with strongly typed models. However, this example demonstrates the usage of the FormCollection object specifically, as requested.

Top comments (0)