March 15, 2015

Handling Get and Post method for Insert/Create operation in mvc dotnet.

In Brief:
Here I am going through the steps to insert data row to database in mvc dotnet with the focus on the following points.

In detail: 
In the previous few examples I have shown how to fetch(read) records from the database.  Here let us have quick glance on create/Insert operation.  

Step1 : Prepare Model class(Business Layer)
As I’m making use of ADO.Net, model class will sit in separate assembly.  So the same is referred here as BusinesLayer. This process is shown in detail in Using Raw ADO.Net/Business object for data accessing in MVC. In my upcoming post I will make use of the Entity Framework for the create/insert operation.

a)To create business Layer,  Right click on solution->Add ->New Project->ClassLibrary->say BusinessLayer->Add.
 Change the class name clsEmployee
 
        public int Id { get;set;}
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public string City { get; set; }
b)After adding above auto implemented class file, in the same way add Class named clsEmployeeBusinesLayer. here i will write below function  to pass the data to the storedprocedure. which intern does the insert operation.

 public void fnInsertNewEmployee(clsEmployee objEmployee)
        {
            string strConectionString = ConfigurationManager.ConnectionStrings["mvcSampleDb"].ConnectionString;

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

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

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

                SqlParameter paramDesignation = new SqlParameter();
                paramDesignation.ParameterName = "@Designation";
                paramDesignation.Value = objEmployee.Designation;
                cmd.Parameters.Add(paramDesignation);

                SqlParameter paramCity = new SqlParameter();
                paramCity.ParameterName = "@City";
                paramCity.Value = objEmployee.City;
                cmd.Parameters.Add(paramCity);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
This stored procedure insert the data whatever it receives from the controller.
Database script: 
create procedure spInsertNewEmployee
@Name varchar(50),
@Gender varchar(10),
@Designation varchar(50),
@City varchar(50)
as Begin
Insert into tblEmployee(Name,Gender,Designation,City)
values(@Name,@Gender,@Designation,@City)
End

create table tblEmployee(id int primary key identity(1,1),Name varchar(50),Gender varchar(10),Designation varchar(50),City varchar(50))
select * from tblEmployee

Step2: Prepare a controller
Add a Controller with name EmployeeController
a) As we need to create a row here I will create new action  method  named   "ActionCreate". This method should respond to "Get" request from browser url, so this is need to decorate with keyword [HttpGet].
This method is only responsible for display the form  where user can enter the data. 

   // GET: /Employee/
        [HttpGet]
        public ActionResult ActionCreate()
        {
            return View();
        }
b) I need to write another action method to intake data from the form. Nothing but data which is posted from the form. Controller looks for the post method with name create() to receive the posted data. 
FormCollection holds the form values posted from the controller in key/Value pair.
Here is that method that is to be mentioned with the [HttpPost]
    [HttpPost]
        public ActionResult ActionCreate( FormCollection formCollection)
        {
            clsEmployee objEmolyee = new clsEmployee();
            //form collection object with particular key/index to retrieve value 
            objEmolyee.Name = formCollection["Name"];
            objEmolyee.Gender = formCollection["Gender"];
            objEmolyee.Designation = formCollection["Designation"];
            objEmolyee.City = formCollection["City"];

            clsEmployeeBusinessLayer objEmployeeBusinessLayer = new clsEmployeeBusinessLayer();
            //handing over the object to businessLayer method fnInsertNewEmployee
            objEmployeeBusinessLayer.fnInsertNewEmployee(objEmolyee);

            return View();
        }
You can observe the overridden method Create() , one responds for the URL Get request. Another one for post from the body.

Step3: create a Form UI:
Right click on Create method of [HttpGet] and Add new View.  I will take this as a strongly typed of type clsEmployee. Select scaffold template of Create. So here framework creates UI on behalf of me.
For a time being I will remove scripts at the bottom also for gender textbox is teaken which is not recommended.We can see later on how to create more customized UI.
 
@model BusinessLayer.clsEmployee @{ ViewBag.Title = "ActionCreate"; } <h2>ActionCreate</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>clsEmployee</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Gender) </div> <div class="editor-field"> @Html.EditorFor(model => model.Gender) @Html.ValidationMessageFor(model => model.Gender) </div> <div class="editor-label"> @Html.LabelFor(model => model.Designation) </div> <div class="editor-field"> @Html.EditorFor(model => model.Designation) @Html.ValidationMessageFor(model => model.Designation) </div> <div class="editor-label"> @Html.LabelFor(model => model.City) </div> <div class="editor-field"> @Html.EditorFor(model => model.City) @Html.ValidationMessageFor(model => model.City) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
On F5:



Final touch:
As you run the application, controller receives "Get" request and responds with the form to fill the data. On user form submission controller receives the posted data on [HttpPost] method and transfers data over to model to save back to the database.
Keep visiting for more updates and feel free to comment your thoughts.
thank you :)