× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Is it possible to use UpdateModel in a controller to populate an object?

James Jensen
Feb 10, 2015
<p>Yes, I use this trick all the time:</p> <pre><code>TryUpdateModel((dynamic)vmObject); </code></pre> <p>The reason you've been having trouble is that <code>TryUpdateModel</code> is a generically-typed method which uses the generic type to determine which properties it should look for. This could be useful if you only wanted to bind specific properties that are declared on an interface, for example. However, when all you know at compile-time is that it's an <code>object</code>, it doesn't know about any properties that can be bound on <code>object</code>s.</p> <p>By casting the object to be <code>dynamic</code>, you allow the system to determine the most appropriate generic signature to use at runtime, based on the runtime type of the object. It's the same as using reflection to generate and invoke a custom generic method signature, but it's far more concise (and has slightly better performance).</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23407713/Is%20it%20possible%20to%20use%20UpdateModel%20in%20a%20controller%20to%20populate%20an%20object?/23407917">Stack Overflow</a>.</p>
comments powered by Disqus