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

public interface IEmployee
        int EmployeeId{set;get;}

        string Country { set; get; }

        string Married { set; get; }

        int DepartmentId { set; get; }

Employee Model:

    public class Employee:IEmployee
        public int EmployeeId { set; get; }

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

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

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

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


        public ActionResult Edit_Post(int employeeId)
            Employee emp = (new EmployeeDbContext()).Employees.Single(x => x.EmployeeId == employeeId);
            if (ModelState.IsValid)
                BusLayer bl = new BusLayer();
                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