Question about binding in asp.net mvc?

524 views Asked by At

How does binding work? Like how many fields have to match up to make a successful bind. Say you got a Product class with 5 fields and only 4 of the fields match up does it still bind?

Also I know they have an exclude for binding but how do you do multiple excludes? Like if I have 2 fields I want to exclude how do you write that?

2

There are 2 answers

0
twk On BEST ANSWER

To exclude any number of fields from binding just list them in the action's bind attribute:

public ActionResult Edit([Bind(Exclude = "Id, Username")] int id, FormCollection collection)

At the same time you can explicite define which fields to update:

TryUpdateModel(user.Person, new string[] { "firstname", "lastname", "email", "phone" });
0
Patrik Potocki On

You could also just type the view

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Person>" %>

And then

[AcceptVerbs(HttpVerbs.Post)]    
public ActionResult Edit([Bind(Exclude = "Id, Username")]Person person)
{
  // Do the logic.
}

Instead of using TryUpdateModel