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
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
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.
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
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
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.
Awesome... its crystal clear...
ReplyDeleteReally thank u sir i am fresher guy and it is easy to learn MVC from this video really great work sir........
ReplyDeletevery cool. I'm real expert after following these videos
ReplyDeleteIts really work well , thanking you sir
ReplyDeleteCant 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.
ReplyDeleteHi 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.
DeleteYou 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..
Deleteemployee.DateOfBirth =
ReplyDeleteConvert.ToDateTime(formCollection["DateOfBirth"]);
give problem string coversion.what i'll do for this?
employee.DateOfBirth = Convert.ToDateTime(rdr["DateOfBirth"]);
Deletegive the data in month/day/year format it will work
Deletei was take dateofbirth as datetime data type in data base
ReplyDeleteand its give error
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
how to resolve error "Keyword not supported: 'metadata'." Please help me.
ReplyDeletewhere u got this error?
Deletemetadata is a reserved keyword in C#. Try some other name if you are planning this 'metadata' name as a variable's name.
Thank You very much sir, I really acquire more knowledge by your lovely tutorials.
ReplyDeleteGenerate Error when Insert data through Stored Procedure
ReplyDeleteSqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
hats off to you sir thank you so much for the tutorials
ReplyDeleteAs a beginner in MVC I would like to know
ReplyDeleteIn this tutorial how can I give [Required] attribute for client level validation with business layer
Procedure or function 'spAddEmp' expects parameter '@Name', which was not supplied.
ReplyDeleteI am getting error as :
ReplyDeleteProcedure or function 'Adprood' expects parameter '@ProductName', which was not supplied.'
but I have given that parameter
what is the problem of
ReplyDeletea namespace connot directly contain members such as field or methods
Sir, How can we post list of object from view to controller?
ReplyDelete