Introduction

In ASP.NET MVC, when we submit a form, we need to collect user input data and send it to the controller.

There are multiple ways:

👉 In this blog, we will learn everything step-by-step in easy words:

1. What is FormCollection?

FormCollection is a class in MVC used to get form values as key-value pairs.

👉 It works like:

All values come in string format.

2. Why We Use FormCollection?

We use FormCollection when:

⚠️ Not recommended for large projects (use Model instead)

3. Create Form in MVC (View)

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "myForm" }))
{
    <div>
        Name: <input type="text" name="Name" />
    </div>

    <div>
        Age: <input type="text" name="Age" />
    </div>

    <div>
        City: <input type="text" name="City" />
    </div>

    <button type="submit">Submit</button>
}

Important

👉 name attribute is VERY IMPORTANT
Controller uses this name to get value

4. Controller (Using FormCollection)

[HttpPost]
public ActionResult Create(FormCollection form)
{
    string name = form["Name"];
    string age = form["Age"];
    string city = form["City"];

    return View();
}

Explanation

5. Convert Data Types

int age = Convert.ToInt32(form["Age"]);

6. Save Data in SQL Server using Model

Model

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

Controller (Save Data)

[HttpPost]
public ActionResult Create(FormCollection form)
{
    Student obj = new Student();

    obj.Name = form["Name"];
    obj.Age = Convert.ToInt32(form["Age"]);
    obj.City = form["City"];

    using (MyDbContext db = new MyDbContext())
    {
        db.Students.Add(obj);
        db.SaveChanges();
    }

    return RedirectToAction("Index");
}

Explanation

7. jQuery with Form Submit (AJAX)

jQuery Code

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $("#myForm").submit(function (e) {
        e.preventDefault();

        var formData = $(this).serialize();

        $.ajax({
            url: '/Home/Create',
            type: 'POST',
            data: formData,
            success: function () {
                alert("Data Saved Successfully");
            }
        });
    });
</script>

Explanation

8. Using FormCollection with Checkbox

var skills = form.GetValues("SelectedSkills");

9. Using FormCollection with Radio Button

var gender = form["Gender"];

10. FormCollection vs Model Binding

11. Important Points

✔ Always match name with key
✔ Convert data types manually
✔ Use Model for real projects
✔ Use AJAX for better UX

12. Common Mistakes

13. Conclusion

FormCollection is useful for quick and dynamic form handling.

You learned: