Monday, 30 December 2013

How to Exclude or Include the properties of Model while Binding in Form POST - ASP.NET MVC



In this article we are going to see how to Exclude or Include the Properties of Model while binding in form post, actually what is the need for explicit specify the properties to bind ? When we send a POST from the form it will bind the all values from the user request , so there is a scenario user can change the value of a read only value in POST Request , then the model will have a impact of changed one, To avoid this kind of things we are explicitly saying that thing kind of properties can be include or exclude from binding using a Attribute called Bind in the parameter.

Inside the Bind attribute we can pass the parameters Include , Exclude with value as string , Properties can be specify by the comma separated. while binding as parameter in the method we have to specify the control name, but for the Bind we have to specify the Property name of the Model.



        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post([Bind(Exclude = "Name", Include = "EmployeeId,Country,Married,DepartmentId")]Employee emp)
        {

            emp.EmployeeName = (new EmployeeDbContext()).Employees.Single(x=>x.EmployeeId==emp.EmployeeId).EmployeeName;

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





From this article we can see how the values from the Form post are bind to the model instance of the input.


No comments:

Post a Comment