Saturday, 28 December 2013

Submit a FORM in ASP.NET MVC

In this article we are going to see how to submit a form to the controller,so let we take a example add a new employee to the list and submit it.

Create a Employee Controller and action in a name of Create which is mention as HttpGet that means it is a Get Request so it is called at the load time, Now for this action create a View.

C#

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }



HTML

@model TestingMvc.Models.Employee
@{
    ViewBag.Title = "Create Employee";
}
<h2>
    Create Employee</h2>
   
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset style="width:300px">
        <legend>Employee</legend>
        <br />
        <div class="editor-label">
            @Html.LabelFor(m => m.EmployeeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(m => m.EmployeeName)
            @Html.ValidationMessageFor(m=>m.EmployeeName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(x => x.Country)
            @Html.ValidationMessageFor(x=>x.Country)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.DepartmentId, "Department")
        </div>
        <div class="editor-field">
            @Html.DropDownList("Departments", new List<SelectListItem>(){
    new SelectListItem(){Text="TECH",Value="1"},
    new SelectListItem(){Text="HR",Value="2"},
    new SelectListItem(){Text="Finance",Value="3"}
    }, "Select Department")
    @Html.ValidationMessageFor(x=>x.DepartmentId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x=>x.Married)
        </div>
        <div class="editor-field">
            @Html.DropDownList("Married",new List<SelectListItem>(){
   new SelectListItem(){Text="Yes",Value="YES"},
   new SelectListItem(){Text="No",Value="NO"}  
   })
   @Html.ValidationMessageFor(x=>x.Married)
        </div>
        <br />
        <input type="submit" value="Create" />
    </fieldset>
}

<br />
@Html.ActionLink("Back to List","Index","Department")

For Post the form we have to create a another action with same name with HttpPost as Attribute.

C# 
        [HttpPost]
        public ActionResult Create(FormCollection form)
        {       
            BusinessLayer bl = new BusinessLayer();
            bl.Create(form["EmployeeName"], form["Country"], form["Married"], int.Parse(form["Departments"]));
            return RedirectToAction("Details", new {                                                                          id=int.Parse(form["Departments"])});           
        }



 Businnes Logic:

    public class BusLayer
    {
        public void Create(string name, string country, string married, int departmentid)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeDbContext"].ConnectionString);
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "EMP_ADD";
                cmd.Parameters.Add(new SqlParameter("@NAME", name));
                cmd.Parameters.Add(new SqlParameter("@DEPT", departmentid));
                cmd.Parameters.Add(new SqlParameter("@COUNTRY", country));
                cmd.Parameters.Add(new SqlParameter("@MARRIED", married));
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }
    }

OUTPUT:


SQL SCRIPT :

CREATE PROCEDURE EMP_ADD(
@NAME VARCHAR(100),
@DEPT VARCHAR(100),
@COUNTRY VARCHAR(20),
@MARRIED VARCHAR(4)
)
AS
BEGIN

SET NOCOUNT ON

      INSERT INTO
      EMPTABLE(
                        NAME,
                        DEPTID,
                        COUNTRY,
                        MARRIED
                  )
      VALUES(
                        UPPER(@NAME),
                        @DEPT,
                        UPPER(@COUNTRY),
                        UPPER(@MARRIED)
                  )

SET NOCOUNT OFF  
     
END



When the Form is submitted  the values and controls are submitted as form collection to the action, so each and every control is stored as Key value pairs.

No comments:

Post a Comment