Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 13 - FormCollection in mvc

Suggested Videos 
Part 10 - Working with multiple tables in MVC
Part 11 - Using business objects as model in mvc
Part 12 - Creating a view to insert data



In this video we will discuss using FormCollection object in mvc and it's purpose. Please watch Part 12, before proceeding with this video.

FormCollection class will automatically receive the posted form values in the controller action method, in key/value pairs. Keys & values can be accessed using key names or index.



We implemented the following "Create" view in Part 12
Create employee view in mvc

We can use the FormCollection to loop thru each key and it's value that is posted to the server.
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
    if (ModelState.IsValid)
    {
        foreach (string key in formCollection.AllKeys)
        {
            Response.Write("Key = " + key + "  ");
            Response.Write("Value = " + formCollection[key]);
            Response.Write("<br/>");
        }
    }
    return View();
}

The output is as shown below
FormCollection in mvc

Create the following stored procedure to insert employee data into tblEmployee table
Create procedure spAddEmployee  
@Name nvarchar(50),  
@Gender nvarchar (10),  
@City nvarchar (50),  
@DateOfBirth DateTime  
as  
Begin  
 Insert into tblEmployee (Name, Gender, City, DateOfBirth)  
 Values (@Name, @Gender, @City, @DateOfBirth)  
End

Add the following method to EmployeeBusinessLayer.cs file.
public void AddEmmployee(Employee employee)
{
    string connectionString =
            ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("spAddEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter paramName = new SqlParameter();
        paramName.ParameterName = "@Name";
        paramName.Value = employee.Name;
        cmd.Parameters.Add(paramName);

        SqlParameter paramGender = new SqlParameter();
        paramGender.ParameterName = "@Gender";
        paramGender.Value = employee.Gender;
        cmd.Parameters.Add(paramGender);

        SqlParameter paramCity = new SqlParameter();
        paramCity.ParameterName = "@City";
        paramCity.Value = employee.City;
        cmd.Parameters.Add(paramCity);

        SqlParameter paramDateOfBirth = new SqlParameter();
        paramDateOfBirth.ParameterName = "@DateOfBirth";
        paramDateOfBirth.Value = employee.DateOfBirth;
        cmd.Parameters.Add(paramDateOfBirth);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

To save form data, to a database table, copy and paste the following code in EmployeeController.cs file.
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
    Employee employee = new Employee();
    // Retrieve form data using form collection
    employee.Name = formCollection["Name"];
    employee.Gender = formCollection["Gender"];
    employee.City = formCollection["City"];
    employee.DateOfBirth = 
        Convert.ToDateTime(formCollection["DateOfBirth"]);

    EmployeeBusinessLayer employeeBusinessLayer = 
        new EmployeeBusinessLayer();

    employeeBusinessLayer.AddEmmployee(employee);
    return RedirectToAction("Index");
}

Do we really have to write all the dirty code of retrieving data from FormCollection and assign it to the properties of "employee" object. The answer is no. This is the job of the modelbinder in MVC. We will discuss modelbinders in our next video.

21 comments:

  1. Really thank u sir i am fresher guy and it is easy to learn MVC from this video really great work sir........

    ReplyDelete
  2. very cool. I'm real expert after following these videos

    ReplyDelete
  3. Its really work well , thanking you sir

    ReplyDelete
  4. Cant seem to get mine to work. I get the "Cannot insert the value NULL into column 'Id', table 'Sample2.dbo.tblEmployee'; column does not allow nulls. INSERT fails." exception. Have I done something wrong in the database? Nowhere in the code do we set the id for the Id column in the database which is my problem. How can I correct this pls.

    ReplyDelete
    Replies
    1. Hi Bard de Klerk.In table u didn't declare primary key that ways u get that exception.you will keep primary key in u r table.

      Delete
    2. You need to set the primary key to auto-increment, or else if you have a non-nullable column, with no default value, if you provide no value it will error.To set up auto-increment in SQL Server Management Studio:Open your table in DesignSelect your column and go to Column PropertiesUnder Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1 But I had to make a new table to set this property..

      Delete
  5. employee.DateOfBirth =
    Convert.ToDateTime(formCollection["DateOfBirth"]);
    give problem string coversion.what i'll do for this?

    ReplyDelete
    Replies
    1. employee.DateOfBirth = Convert.ToDateTime(rdr["DateOfBirth"]);

      Delete
    2. give the data in month/day/year format it will work

      Delete
  6. i was take dateofbirth as datetime data type in data base
    and its give error

    SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

    ReplyDelete
  7. how to resolve error "Keyword not supported: 'metadata'." Please help me.

    ReplyDelete
    Replies
    1. where u got this error?
      metadata is a reserved keyword in C#. Try some other name if you are planning this 'metadata' name as a variable's name.

      Delete
  8. Thank You very much sir, I really acquire more knowledge by your lovely tutorials.

    ReplyDelete
  9. Generate Error when Insert data through Stored Procedure




    SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

    ReplyDelete
  10. hats off to you sir thank you so much for the tutorials

    ReplyDelete
  11. As a beginner in MVC I would like to know
    In this tutorial how can I give [Required] attribute for client level validation with business layer

    ReplyDelete
  12. Procedure or function 'spAddEmp' expects parameter '@Name', which was not supplied.

    ReplyDelete
  13. I am getting error as :
    Procedure or function 'Adprood' expects parameter '@ProductName', which was not supplied.'

    but I have given that parameter

    ReplyDelete
  14. what is the problem of
    a namespace connot directly contain members such as field or methods

    ReplyDelete
  15. Sir, How can we post list of object from view to controller?

    ReplyDelete

It would be great if you can help share these free resources