Need guide line for MVC action method with Bind attribute

Solution 1:

Bind attribute lets you "fine-tune" the model-binding process of certain parameter Type, without registering a custom ModelBinder specific to the Type.

For example, assume your Action is expecting a Person parameter defined as follows:

public class Person
{
    public Person(string firstName, string lastName, Gender gender)
    {
        this.FirstName = firstName;
        this.LastName = lastName;

        if (gender == Gender.Male)
            this.FullName = "Mr. " + this.FirstName + " " + this.LastName;
        else
            this.FullName = "Mrs. " + this.FirstName + " " + this.LastName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Gender Gender { get; set; }

    // 'FullName' is a computed column:
    public string FullName { get; set; }
}

And the Action:

public ActionResult Edit(Person person)
{
    ...
}

Now, if someone is posting the following JSON:

{
    "FirstName":"John",
    "LastName":"Smith",
    "Gender":"Male",
    "FullName":"Mrs. John Smith"
}

Your Action will now have a person with the wrong FullName ('Mrs' instead of 'Mr').

To avoid such behavior you can use the Bind attribute and explicitly exclude the FullName property from the binding process ('Black-list'):

public ActionResult Edit([Bind(Exclude="FullName")] Person person)
{
    ...
}

Alternatively, you can use Include to ignore ('Black-list') all properties and only include ('White-list') the specified properties:

public ActionResult Edit([Bind(Include="FirstName,LastName,Gender")] Person person)
{
    ...
}

More info on MSDN.

Solution 2:

When this action is executed the MVC model binder will use the request parameters to populate the user parameter's properties, as you may already know. However, the Bind attribute tells the model binder to only populate properties with names specified.

So in this case only the Username, FullName and Email properties will be populated. All others will be ignored.

See here for more details: http://ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/