Monday 30 December 2013

Bind a Model for form post using interface - ASP.NET MVC



In this article we are going to see how to bind a model values from the form post , by ignore the exclude properties for binding.

By passing the Interface type in update model ,it will update the particular properties which are present in Interface to the object

Interface:
public interface IEmployee
    {
        int EmployeeId{set;get;}

        string Country { set; get; }

        string Married { set; get; }

        int DepartmentId { set; get; }
    }



Employee Model:

    [Table("EMPTABLE")]
    public class Employee:IEmployee
    {
        [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; }
    }



C#:

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int employeeId)
        {
            Employee emp = (new EmployeeDbContext()).Employees.Single(x => x.EmployeeId == employeeId);
            TryUpdateModel<IEmployee>(emp);
            if (ModelState.IsValid)
            {
                BusLayer bl = new BusLayer();
                bl.Update(emp);
                return RedirectToAction("Details", new { id=emp.DepartmentId});
            }
            return View(emp);
        }




From this article you can learn how to bind the model values from the form post using the interface. which will help to ignore the unwanted values to bind in form post.

No comments:

Post a Comment