20 Jun 2012

MVC Bind Attribute

Just a quick tip. If you want to use the Bind attribute to set the binding whitelist/blacklist (include/exclude) settings, you may have seen many examples where they set the attribute in the Controller Action signature i.e.
public ActionResult UpdateThing([Bind(Exclude="IsSuperUser")]UserEntity model)

However, I think the following approach is nicer. First define your ViewModel, which simply extends your entity model. Note that we define the Bind Attribute on the class definition itself.

public class VM_User : UserEntity {}

Then you just bind from the ViewModel in your Action.

public ActionResult UpdateThing(VM_User model)
To copy property data back from your ViewModel to your entity model, I favour ValueInjecter. I wrote a special Injection class for this purpose: http://zootfroot.blogspot.co.uk/2012/06/custom-valueinjecter-injection-to-use.html

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!