Note that there are some explanatory texts on larger screens.

plurals
  1. POBinding non-sequential lists with a custom model binder
    primarykey
    data
    text
    <p>I know that if I want to bind non-sequential elements to a list in MVC I can use the <code>Index</code> syntax described <a href="http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx" rel="noreferrer">here</a>.</p> <p>However, I'm unable to get remote validation to work with this (using the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute%28v=vs.98%29.aspx" rel="noreferrer"><code>Remote</code></a> attribute). </p> <p>For example, if I had a model like this:</p> <pre><code>public class AddUsers { public List&lt;User&gt; Users { get; set; } public string Comment { get; set; } } public class User { [Remote("UsernameAvailable", "User")] public string Name { get; set; } } </code></pre> <p>Then suppose in my view I have the following (I'm deliberately leaving out Html helpers I'm using for clarity):</p> <pre><code>&lt;input type="hidden" name="Users.Index" value="foo" /&gt; &lt;input type="text" name="Users[foo].Name" /&gt; &lt;input type="hidden" name="Users.Index" value="bar" /&gt; &lt;input type="text" name="Users[bar].Name" /&gt; </code></pre> <p>In a form post, the <code>Index</code> field goes along for the ride, which helps the model binder bind everything nicely, like:</p> <pre><code>Comment=bla&amp;Users.Index=foo&amp;Users[foo].Name=john&amp;Users.Index=bar&amp;Users[bar].Name=bob </code></pre> <p>But when remote validation triggers, only this is sent to my action (two separate requests, one for each item being validated):</p> <pre><code>Users[foo].Name=john Users[bar].Name=bob </code></pre> <p>Without an <code>Index</code>, The model binder doesn't know what to do with this. It can neither bind to a <code>User</code>, a <code>List&lt;User&gt;</code>, nor an <code>AddUser</code>.</p> <p>Which brings me to my question.</p> <p>Would there be a way to write a custom model binder that can handle non-sequential lists without needing to use the <code>Index</code> notation? I must admit that it is difficult for me to see why the <code>Index</code> notation would be necessary (except perhaps as an optimization of some kind).</p> <p>I'm using MVC 4, and .NET 4.5.</p> <p><strong>Note:</strong> I've never messed around with custom model binders before, so I'm really just looking for some general guidance about whether it would be possible (or just a dead end), and possibly some pointers for getting started.</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.
 

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