HI WELCOME TO Sirees

Part 21 - Including and excluding properties from model binding using bind attribute

Leave a Comment
we will discuss, including and excluding properties from model binding using BIND attribute. 

 we have seen how to include and exclude properties from model binding, by passing a string array to UpdateModel() method. There is another way to do the same thing using "Bind" attribute.


Modify "Edit_Post()" controller action method that is present in "EmployeeController.cs" file, as shown below.
[HttpPost]
[ActionName("Edit")]
public ActionResult Edit_Post([Bind(Include = "Id, Gender, City, DateOfBirth")] Employee employee)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    employee.Name = employeeBusinessLayer.Employees.Single(x => x.ID == employee.ID).Name;

    if (ModelState.IsValid)
    {
        employeeBusinessLayer.SaveEmployee(employee);

        return RedirectToAction("Index");
    }

    return View(employee);
}

Notice that, we are using "BIND" attribute and specifying the properties that we want to include in model binding. Since, "Name" property is not specified in the INCLUDE list, it will be excluded from model binding.
public ActionResult Edit_Post([Bind(Include = "Id, Gender, City, DateOfBirth")] Employee employee)

At this point, run the application and navigate to "http://localhost/MVCDemo/Employee/Edit/1". Click "Save" button, you will get a "Model" validation error stating - "The Name field is required".

This is because, we marked "Name" property in "Employee" class with "Required" attribute. Remove the "Required" attribute from "Name" property.
public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    [Required]
    public string Gender { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public DateTime? DateOfBirth { get; set; }
}

So, if we were to generate a post request using fiddler as we did in the previous session, "Name" property of the "Employee" object will not be updated.

Alternatively, to exclude properties from binding, we can specify the exclude list using "Bind" attribute as shown below. 
[HttpPost]
[ActionName("Edit")]
public ActionResult Edit_Post([Bind(Exclude = "Name")] Employee employee)
{
    // Rest of the method implementation remains the same
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.