Sunday 29 December 2013

Update the Selected Properties of the Model in Form Post ASP.NET MVC

In this article we are going to see how to update the Model of selected properties in the Form Post , For that we  have to understand about UpdateModel method, this method is used to update the model type variable value with the form post value. When there is a null value in the required column then the error will raise to avoid error, try to use the TryUpdateModel  in this method when validate the posted value if any model validation error is there then it will return false.

Try to use ModelState.IsValid property to check that the Model doesn't have any validation error.There is a second parameter in which series of string array parameter can be passed which specifies the property names.


 Controller:

        [HttpGet]
        [ActionName("Edit")]
        public ActionResult Edit_Get(int id)
        {
            Employee emp = (new EmployeeDbContext()).Employees.Where(x => x.EmployeeId == id).FirstOrDefault();
            return View(emp);
        }

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {


            Employee emp = (new EmployeeDbContext()).Employees.Single(x=>x.EmployeeId==id);
            TryUpdateModel(emp,new string[]{"Country","Married","DepartmentId"});

            if (ModelState.IsValid)
            {
                BusLayer bl = new BusLayer();
                bl.Update(emp);
                return RedirectToAction("Details", new { id=emp.DepartmentId});
            }
            return View(emp);
        }

Model:

[Table("EMPTABLE")]
    public class Employee
    {
        [Column("ID")]       
        public int EmployeeId { set; get; }

        [Column("NAME")]
        [Required(ErrorMessage="Please Fill Employee Name")]       
        public string EmployeeName { set; get; }

        [Column("COUNTRY")]
        [Required(ErrorMessage="Please Fill the Country")]
        public string Country { set; get; }

        [Column("MARRIED")]
        [Required(ErrorMessage="Please Specify the Married y/n")]
        public string Married { set; get; }

        [Column("DEPTID")]
        [Required(ErrorMessage="Please specify the Department")]
        public int DepartmentId { set; get; }
    }


Business Layer:

public class BusLayer
    {
        public void Update(Employee emp)
        {
            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_Upd";
                cmd.Parameters.Add(new SqlParameter("@ID", emp.EmployeeId));
                cmd.Parameters.Add(new SqlParameter("@NAME", emp.EmployeeName));
                cmd.Parameters.Add(new SqlParameter("@DEPT", emp.DepartmentId));
                cmd.Parameters.Add(new SqlParameter("@COUNTRY", emp.Country));
                cmd.Parameters.Add(new SqlParameter("@MARRIED", emp.Married));
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }

        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();
            }
        }
    }


From this article you can learn how to bind  the selected Model properties for submit from a Form.

No comments:

Post a Comment