Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat, exactly, does a modelbinder do? How to use it effectively?
    primarykey
    data
    text
    <p>I was researching something and came across <a href="http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/" rel="nofollow">this blog post at buildstarted.com</a> about model binders. It actually works pretty darn well for my purposes but I am not sure exactly whats going on behind the scenes. What I did was create a custom ModelBinder called <code>USerModelBinder</code>:</p> <pre><code>public class UserModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult value = bindingContext.ValueProvider.GetValue("id"); MyEntities db = new MyEntities(); User user = db.Users.SingleOrDefault(u =&gt; u.UserName == value.AttemptedValue); return user; } } </code></pre> <p>Then in my <code>Global.asax.cs</code> I have:</p> <p><code>ModelBinders.Binders.Add(typeof(User), new UserModelBinder());</code></p> <p>My understanding is that using the model binder allows me to NOT have to use the following lines in every controller action that involves a "User". So instead of passing in an "id" to the action, the modelbinder intercepts the id, fetches the correct "item"(User in my case) and forwards it to the action for processing.</p> <pre><code> MyEntities db = new MyEntities(); User user = db.Users.SingleOrDefault(u =&gt; u.UserName == value.AttemptedValue); </code></pre> <p>I also tried using an annotation on my User class instead of using the line in Global.asax.cs:</p> <pre><code>[ModelBinder(typeof(UserModelBinder))] public partial class User { } </code></pre> <p>I'm not looking for a 30 page white paper but I have no idea how the model binder does what it does. I just want to understand what happens from when a request is made to the time it is served. All this stuff "just working" is not acceptable to me, lol. Also, is there any difference between using the annotation versus adding it in Global.asax.cs? They seem to work the same in my testing but are there any gotchas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload