Note that there are some explanatory texts on larger screens.

plurals
  1. POPolymorphic model binding
    primarykey
    data
    text
    <p>This question has been <a href="https://stackoverflow.com/questions/4012217/asp-net-mvc-2-binding-to-abstract-model">asked before</a> in earlier versions of MVC. There is also <a href="http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/" rel="noreferrer">this blog entry</a> about a way to work around the problem. I'm wondering if MVC3 has introduced anything that might help, or if there are any other options.</p> <p>In a nutshell. Here's the situation. I have an abstract base model, and 2 concrete subclasses. I have a strongly typed view that renders the models with <code>EditorForModel()</code>. Then I have custom templates to render each concrete type.</p> <p>The problem comes at post time. If I make the post action method take the base class as the parameter, then MVC can't create an abstract version of it (which i would not want anyways, i'd want it to create the actual concrete type). If I create multiple post action methods that vary only by parameter signature, then MVC complains that it's ambiguous.</p> <p>So as far as I can tell, I have a few choices on how to solve this proble. I don't like any of them for various reasons, but i will list them here:</p> <ol> <li>Create a custom model binder as Darin suggests in the first post I linked to.</li> <li>Create a discriminator attribute as the second post I linked to suggests.</li> <li>Post to different action methods based on type</li> <li>???</li> </ol> <p>I don't like 1, because it is basically configuration that is hidden. Some other developer working on the code may not know about it and waste a lot of time trying to figure out why things break when changes things.</p> <p>I don't like 2, because it seems kind of hacky. But, i'm leaning towards this approach.</p> <p>I don't like 3, because that means violating DRY. </p> <p>Any other suggestions?</p> <p>Edit: </p> <p>I decided to go with Darin's method, but made a slight change. I added this to my abstract model:</p> <pre><code>[HiddenInput(DisplayValue = false)] public string ConcreteModelType { get { return this.GetType().ToString(); }} </code></pre> <p>Then a hidden automatically gets generated in my <code>DisplayForModel()</code>. The only thing you have to remember is that if you're not using <code>DisplayForModel()</code>, you'll have to add it yourself.</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.
 

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