Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I have had the same issue in one of my applications. I solved it by creating a custom IModelBinder inheriting from DefaultModelBinder and registered it with the particular type I'm binding.</p> <p>The trick is to use <code>session.Load&lt;&gt;</code> which only creates a typed reference to the entity without querying the database. (<a href="http://ayende.com/blog/3988/nhibernate-the-difference-between-get-load-and-querying-by-id" rel="nofollow">Read more about session.Load here in Ayende's blog</a>)</p> <pre><code>/// &lt;summary&gt; /// Base for binding references. Usually displayed in dropdowns /// &lt;/summary&gt; public class ReferenceBinder&lt;T&gt; : DefaultModelBinder where T : class { private readonly ISession session; public ReferenceBinder(ISession session) { this.session = session; } public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var idName = CreateSubPropertyName(bindingContext.ModelName, "ID"); ValueProviderResult result = bindingContext.ValueProvider.GetValue(idName); int value; return (int.TryParse(result.AttemptedValue, out value)) ? this.session.Load&lt;T&gt;(value) : null; } } </code></pre> <p>In your example you would do something like this in Global.asax:</p> <pre><code>ModelBinders.Binders.Add(typeof(Position), new ReferenceBinder&lt;Position&gt;(&lt;pass your current session implementation or use DI/IoC&gt;)); </code></pre> <p>(I'm using Castle Windsor to create the actual binder and populate session in my implementation)</p> <p>Assuming your domain model is:</p> <pre><code> public class Player { public virtual Position Position {get;set;} } public class Position { public virtual int ID {get;private set;} } </code></pre> <p>And your postback looks like this:</p> <pre><code>"Position.ID" = &lt;id from dropdown&gt; </code></pre> <p>EDIT: You should probably use a DTO approach with dedicated view models. I've learned this later on. <a href="http://stevesmithblog.com/blog/binding-in-asp-net-mvc/" rel="nofollow">Have a look here for a quick start</a>.</p>
    singulars
    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.
    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