<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://shazwazza.com/rss/xslt"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>Shazwazza</title>
    <link>https://shazwazza.com/</link>
    <description>My blog which is pretty much just all about coding</description>
    <generator>Articulate, blogging built on Umbraco</generator>
    <image>
      <url>/media/0libq25y/frog.png?rmode=max&amp;v=1da0e911f4e6890</url>
      <title>Shazwazza</title>
      <link>https://shazwazza.com/</link>
    </image>
    <item>
      <guid isPermaLink="false">1309</guid>
      <link>https://shazwazza.com/post/controller-scoped-model-binding-in-aspnet-core/</link>
      <category>ASP.Net</category>
      <title>Controller Scoped Model Binding in ASP.NET Core</title>
      <description>&lt;p&gt;Want to avoid &lt;em&gt;[FromBody]&lt;/em&gt; attributes everywhere? Don’t want to use &lt;em&gt;[ApiController]&lt;/em&gt; strict conventions? Don’t want to apply &lt;em&gt;IInputFormatter&lt;/em&gt;’s globally?&lt;/p&gt;
&lt;p&gt;ASP.NET Core MVC is super flexible but it very much caters towards configuring everything at a global level. Perhaps you are building a framework or library or a CMS in .NET Core? In which case you generally want to be as unobtrusive as possible so mucking around with global MVC configuration isn’t really acceptable. The traditional way of dealing with this is by applying configuration directly to controllers which generally means using controller base classes and attributes. This isn’t super pretty but it works in almost all cases from applying authorization/resource/action/exception/result filters to api conventions. However this doesn’t work for model binding.&lt;/p&gt;
&lt;h2&gt;Model binding vs formatters&lt;/h2&gt;
&lt;p&gt;Model binding comes in 2 flavors: formatters for deserializing the request body (like JSON) into models  and value providers for getting data from other places like form body, query string, headers, etc… Both of these things internally in MVC use model binders though typically the language used for binding the request body are called formatters. The problem with formatters (which are of type &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.iinputformatter?view=aspnetcore-3.1" target="_blank"&gt;IInputFormatter&lt;/a&gt;) is that they are only applied at the global level as part of &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.mvcoptions.inputformatters?view=aspnetcore-3.1#Microsoft_AspNetCore_Mvc_MvcOptions_InputFormatters" target="_blank"&gt;MvcOptions&lt;/a&gt; which are in turn passed along to a special model binder called &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.binders.bodymodelbinder?view=aspnetcore-3.1" target="_blank"&gt;BodyModelBinder&lt;/a&gt;. Working with &lt;em&gt;IInputFormatter&lt;/em&gt; at the controller level is almost impossible.&lt;/p&gt;
&lt;p&gt;There seems to be a couple options that look like you might be able to apply a custom &lt;em&gt;IInputFormatter&lt;/em&gt; to a specific controller:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Create a custom &lt;em&gt;IModelBinderProvider&lt;/em&gt; – this unfortunately will not work because the &lt;em&gt;ModelBinderProviderContext&lt;/em&gt; doesn’t provide the &lt;em&gt;ControllerActionDescriptor&lt;/em&gt; executing so you cannot apply this provider to certain controllers/actions (&lt;a rel="noopener" href="https://github.com/dotnet/aspnetcore/issues/21724" target="_blank"&gt;though this should be possible&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;Assign a custom &lt;em&gt;IModelBinderFactory&lt;/em&gt; to the controller explicitly by assigning &lt;em&gt;ControllerBase.ModelBinderFactory &lt;/em&gt;in the controllers constructor – this unfortunately doesn’t work because the &lt;em&gt;ControllerBase.ModelBinderFactory &lt;/em&gt;&lt;a rel="noopener" href="https://github.com/dotnet/aspnetcore/issues/21724" target="_blank"&gt;isn’t used for body model binding&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;So how does [ApiController] attribute work?&lt;/h2&gt;
&lt;p&gt;The &lt;em&gt;[ApiController]&lt;/em&gt; attribute does quite a lot of things and &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1#apicontroller-attribute" target="_blank"&gt;configures your controller in a very opinionated way&lt;/a&gt;. It almost does what I want and it somehow magically does this&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[FromBody] is inferred for complex type parameters&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That’s great! It’s what I want to do but I don’t want to use the &lt;em&gt;[ApiController]&lt;/em&gt; attribute since it applies too many conventions and the only way to toggle these …. is again at the global level :/ This also still doesn’t solve the problem of applying a specific &lt;em&gt;IInputFormatter&lt;/em&gt; to be used for the model binding but it’s a step in the right direction.&lt;/p&gt;
&lt;p&gt;The way that the &lt;em&gt;[ApiController]&lt;/em&gt; attribute works is by using MVC’s &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/application-model?view=aspnetcore-3.1" target="_blank"&gt;“application model”&lt;/a&gt; which is done by implementing &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/application-model?view=aspnetcore-3.1#iapplicationmodelprovider" target="_blank"&gt;IApplicationModelProvider&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;A custom IApplicationModelProvider&lt;/h2&gt;
&lt;p&gt;Taking some inspiration from the way [ApiController] attribute works we can have a look at the source of the application model that makes this happen: &lt;a rel="noopener" href="https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/ApplicationModels/ApiBehaviorApplicationModelProvider.cs" target="_blank"&gt;ApiBehaviorApplicationModelProvider&lt;/a&gt;. This basically assigns a bunch of &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.applicationmodels.iactionmodelconvention?view=aspnetcore-3.1" target="_blank"&gt;IActionModelConvention&lt;/a&gt;’s: &lt;em&gt;ApiVisibilityConvention&lt;/em&gt;, &lt;em&gt;ClientErrorResultFilterConvention&lt;/em&gt;, &lt;em&gt;InvalidModelStateFilterConvention&lt;/em&gt;, &lt;em&gt;ConsumesConstraintForFormFileParameterConvention&lt;/em&gt;, &lt;em&gt;ApiConventionApplicationModelConvention&lt;/em&gt;, and &lt;em&gt;InferParameterBindingInfoConvention&lt;/em&gt;. The last one &lt;strong&gt;InferParameterBindingInfoConvention &lt;/strong&gt;is the important one that magically makes complex type parameters bind from the request body like JSON like good old WebApi used to do.&lt;/p&gt;
&lt;p&gt;So we can make our own application model to target our own controllers and use a custom &lt;em&gt;IActionModelConvention&lt;/em&gt; to apply a custom body model binder:&lt;/p&gt;
&lt;pre&gt;&lt;code class="lang-csharp"&gt;
public class MyApplicationModelProvider : IApplicationModelProvider
{
    public MyApplicationModelProvider(IModelMetadataProvider modelMetadataProvider)
    {
        ActionModelConventions = new List&amp;lt;IActionModelConvention&amp;gt;()
        {
            // Ensure complex models are bound from request body
            new InferParameterBindingInfoConvention(modelMetadataProvider),
            // Apply custom IInputFormatter to the request body
            new MyModelBinderConvention()
        };
    }

    public List&amp;lt;IActionModelConvention&amp;gt; ActionModelConventions { get; }

    public int Order =&amp;gt; 0;

    public void OnProvidersExecuted(ApplicationModelProviderContext context)
    {
    }

    public void OnProvidersExecuting(ApplicationModelProviderContext context)
    {
        foreach (var controller in context.Result.Controllers)
        {
            // apply conventions to all actions if attributed with [MyController]
            if (IsMyController(controller))
                foreach (var action in controller.Actions)
                    foreach (var convention in ActionModelConventions)
                        convention.Apply(action);
        }
    }

    // returns true if the controller is attributed with [MyController]
    private bool IsMyController(ControllerModel controller)
        =&amp;gt; controller.Attributes.OfType&amp;lt;MyControllerAttribute&amp;gt;().Any();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the custom convention:&lt;/p&gt;
&lt;pre&gt;&lt;code class="lang-csharp"&gt;
public class MyModelBinderConvention : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        foreach (var p in action.Parameters
            // the InferParameterBindingInfoConvention must execute first,
            // which assigns this BindingSource, so if that is assigned
            // we can then assign a custom BinderType to be used.
            .Where(p =&amp;gt; p.BindingInfo?.BindingSource == BindingSource.Body))
        {
            p.BindingInfo.BinderType = typeof(MyModelBinder);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on the above application model conventions, any controller attributed with our custom &lt;em&gt;[MyController]&lt;/em&gt; attribute will have these conventions applied to all of it’s actions. With the above, any complex model that will be bound from the request body will use the &lt;em&gt;IModelBinder&lt;/em&gt; type: &lt;em&gt;MyModelBinder, &lt;/em&gt;so here’s how that implementation could look:&lt;/p&gt;
&lt;pre&gt;&lt;code class="lang-csharp"&gt;
// inherit from BodyModelBinder - it does a bunch of magic like caching
// that we don't want to miss out on
public class MyModelBinder : BodyModelBinder
{
    // TODO: You can inject other dependencies to pass to GetInputFormatter
    public MyModelBinder(IHttpRequestStreamReaderFactory readerFactory)
        : base(GetInputFormatter(), readerFactory)
    {
    }

    private static IInputFormatter[] GetInputFormatter()
    {  
        return new IInputFormatter[]
        {
            // TODO: Return any IInputFormatter you want
            new MyInputFormatter()
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The last thing to do is wire it up in DI:&lt;/p&gt;
&lt;pre&gt;&lt;code class="lang-csharp"&gt;
services.TryAddSingleton&amp;lt;MyModelBinder&amp;gt;();            
services.TryAddEnumerable(
    ServiceDescriptor.Transient&amp;lt;IApplicationModelProvider,
    MyApplicationModelProvider&amp;gt;());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s a reasonable amount of plumbing!&lt;/p&gt;
&lt;p&gt;It could certainly be simpler to configure a body model binder at the controller level but at least there’s actually a way to do it. For a single controller this is quite a lot of work but for a lot of controllers the MVC “application mode” is quite brilliant! … it just took a lot of source code reading to figure that out :)&lt;/p&gt;</description>
      <pubDate>Thu, 23 Mar 2023 15:09:49 Z</pubDate>
      <a10:updated>2023-03-23T15:09:49Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1184</guid>
      <link>https://shazwazza.com/post/model-binding-with-fromservices-in-aspnet-5/</link>
      <category>ASP.Net</category>
      <title>Model binding with FromServices in ASP.Net 5</title>
      <description>&lt;p&gt;Here’s a new nifty feature I found in ASP.Net 5 – you can construct your model during model binding with IoC without any additional work. This is available on the dev branch on GitHub and is based on something called &lt;a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/ModelBinders/ServicesModelBinder.cs" target="_blank"&gt;&lt;em&gt;ServicesModelBinder&lt;/em&gt;&lt;/a&gt;. This is actually pretty cool because it means that you can have a model wired up with all of it’s dependencies based on IoC and then bound to your controller action’s parameters.&lt;/p&gt; &lt;h2&gt;FromServices attribute&lt;/h2&gt; &lt;p&gt;There’s a new attribute called &lt;a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.ModelBinding/BinderMetadata/FromServicesAttribute.cs" target="_blank"&gt;&lt;em&gt;FromServices&lt;/em&gt;&lt;/a&gt; which is what you use to enable this functionality. For example:&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; async Task&amp;lt;ActionResult&amp;gt; GetProduct(
    [FromServices]ProductModel product)
{

}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;What this attribute does is tell MVC to bind the model using &lt;a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.ModelBinding/BinderMetadata/IServiceActivatorBinderMetadata.cs" target="_blank"&gt;&lt;em&gt;IServiceActivatorBinderMetadata&lt;/em&gt;&lt;/a&gt; which is what the &lt;em&gt;FromServices&lt;/em&gt; attribute implements. This in turn tells MVC to lookup the model binder that is aware of &lt;em&gt;IServiceActivatorBinderMetadata &lt;/em&gt;which happens to be the &lt;em&gt;ServicesModelBinder.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;ServicesModelBinder&lt;/h2&gt;
&lt;p&gt;This model binder is pretty simple, it’s just going to resolve the model type from your IoC container. That could be pretty useful if you need to build up your model properties based on other services. I think some people might argue that this isn’t great practice because this is putting the binding logic in to the model itself instead of using a separate class to perform the binding logic. I suppose it’s up to the individual developer as to what their preference is. You can of course still create your own &lt;em&gt;&lt;a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/IModelBinder.cs" target="_blank"&gt;IModelBinder&lt;/a&gt;&lt;/em&gt; and use the &lt;em&gt;&lt;a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.ModelBinding/BinderMetadata/ModelBinderAttribute.cs" target="_blank"&gt;ModelBinderAttribute&lt;/a&gt;&lt;/em&gt; to keep the model binding logic in the binder itself.&lt;/p&gt;
&lt;h2&gt;Incoming route values&lt;/h2&gt;
&lt;p&gt;Since the model is being created from IoC, how do you get the current route values to build up your model? To do that you’d put a constructor dependency on &lt;em&gt;IContextAccessor&amp;lt;ActionContext&amp;gt;. &lt;/em&gt;This will give you all of the current route values, &lt;em&gt;HttpContext&lt;/em&gt;, etc… basically everything you’d need to pull the data out of the current request to build your model. &lt;/p&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;p&gt;Given the above GetProduct example, the &lt;em&gt;ProductModel&lt;/em&gt; class could look like:&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ProductModel
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; ProductModel(IContextAccessor&amp;lt;ActionContext&amp;gt; action, IProductService prodService)
    {
        &lt;span class="rem"&gt;//TODO: Do some error checking...&lt;/span&gt;
        var productId = action.Value.RouteData.Values[&lt;span class="str"&gt;"product"&lt;/span&gt;];
        Value = prodService.Get(productId);
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IProduct Value { get; &lt;span class="kwrd"&gt;private&lt;/span&gt; set; }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;This is pretty simple – the &lt;em&gt;IProduct&lt;/em&gt; is looked up from the &lt;em&gt;IProductService&lt;/em&gt; based on the incoming ‘product’ route value. Then in the controller you could just do: &lt;em&gt;product.Value&lt;/em&gt; to get the value for &lt;em&gt;IProduct&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;You then need to ensure that both IProductService and ProductModel are registered as services in your container and it’s really important that the &lt;em&gt;ProductModel&lt;/em&gt; is registered as a Transient object &lt;/p&gt;</description>
      <pubDate>Thu, 23 Mar 2023 15:08:15 Z</pubDate>
      <a10:updated>2023-03-23T15:08:15Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1211</guid>
      <link>https://shazwazza.com/post/custom-mvc-modelbinder-with-complex-modelsobjectsinterfaces-using-built-in-mvc-validation/</link>
      <category>ASP.Net</category>
      <title>Custom MVC ModelBinder with Complex Models/Objects/Interfaces using built in MVC Validation</title>
      <description>&lt;p&gt;I’ve been creating some cool stuff using &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx" target="_blank"&gt;ASP.Net MVC 3&lt;/a&gt; lately and came across a situation where I’d like to have quite a complex model/object bound to an Action on my Controller based on a set of posted values from a form. In order to do this, a custom &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelbinders.aspx" target="_blank"&gt;ModelBinder&lt;/a&gt;&lt;em&gt;&lt;/em&gt; is necessary to collect the data from the posted values, turn it into my custom object, and bind that object to my Action’s parameter. The easy part is to write code to turn the posted values into my custom object and return it, the tricky part is trying to get the in-built back-end MVC validation working for my model… which is currently using &lt;em&gt;&lt;a href="http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs" target="_blank"&gt;DataAnnotations&lt;/a&gt;&lt;/em&gt;. I really didn’t feel like writing my own logic to validate my model against &lt;em&gt;&lt;a href="http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs" target="_blank"&gt;DataAnnotations&lt;/a&gt;&lt;/em&gt; and also didn’t want to write the logic to take into account that &lt;em&gt;&lt;a href="http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs" target="_blank"&gt;DataAnnotations&lt;/a&gt;&lt;/em&gt; might not be the current developers validation provider of choice. So after much digging through the source of MVC and using &lt;a href="http://www.red-gate.com/products/reflector/" target="_blank"&gt;Reflector&lt;/a&gt;, I finally found the solution.&amp;nbsp; To better describe the concept, here’s an example of the issue:&lt;/p&gt; &lt;p&gt;Each &lt;em&gt;IMyObject&lt;/em&gt; has many properties: &lt;em&gt;IProperty&lt;/em&gt;. Each &lt;em&gt;IProperty&lt;/em&gt; is of a type: &lt;em&gt;IType&lt;/em&gt; and each &lt;em&gt;IType&lt;/em&gt; has a model which is used to render out the editor in MVC (&lt;a href="http://msdn.microsoft.com/en-us/library/ee402949.aspx" target="_blank"&gt;EditorFor&lt;/a&gt;&lt;em&gt;&lt;/em&gt;)&lt;/p&gt; &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:68eead81-30aa-4103-b787-a53eac690c6c" class="wlWriterSmartContent"&gt;&lt;pre style="background-color: white; width: 642px; height: 394px; overflow: hidden"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;interface&lt;/span&gt;&lt;span style="color: #000000"&gt; IMyObject
{
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&lt;span style="color: #000000"&gt; Id { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&lt;span style="color: #000000"&gt; Name { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    IEnumerable&lt;/span&gt;&lt;span style="color: #000000"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000"&gt;IProperty&lt;/span&gt;&lt;span style="color: #000000"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000"&gt; Properties { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
}

&lt;/span&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;interface&lt;/span&gt;&lt;span style="color: #000000"&gt; IProperty
{
    Guid Id { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;set&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&lt;span style="color: #000000"&gt; Alias { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;set&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&lt;span style="color: #000000"&gt; Name { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;set&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    IType DataType { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
}

&lt;/span&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;interface&lt;/span&gt;&lt;span style="color: #000000"&gt; IType        
{
    Guid Id { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&lt;span style="color: #000000"&gt; Name { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&lt;span style="color: #000000"&gt; Alias { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&lt;span style="color: #000000"&gt; EditorModel { &lt;/span&gt;&lt;span style="color: #0000ff"&gt;get&lt;/span&gt;&lt;span style="color: #000000"&gt;; }
}

&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;
&lt;p&gt;So my controller’s Action looks something like this:&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:090cdce2-c708-45ea-86fe-f5ad941c6a2b" class="wlWriterSmartContent"&gt;&lt;pre style="background-color: white; width: 642px; height: 174px; overflow: hidden"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;override&lt;/span&gt;&lt;span style="color: #000000"&gt; ActionResult Edit(IMyObject obj)
{
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;if&lt;/span&gt;&lt;span style="color: #000000"&gt; (&lt;/span&gt;&lt;span style="color: #000000"&gt;!&lt;/span&gt;&lt;span style="color: #000000"&gt;ModelState.IsValid)
        &lt;/span&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt;&lt;span style="color: #000000"&gt; View(obj);
 
    &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;Save some data and do other stuff...&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;    
}&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;
&lt;p&gt;Initially my model binder looks like this which is the ‘easy’ part that converts the posted values into an &lt;em&gt;IMyObject&lt;/em&gt; object with all of it’s values filled in:&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:decbd6d0-0b2b-4bd7-8d67-238c678aa4d7" class="wlWriterSmartContent"&gt;&lt;pre style="background-color: white; width: 642px; height: 658px; overflow: auto"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #000000"&gt;[ModelBinderType(&lt;/span&gt;&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000"&gt;(IMyObject))]
&lt;/span&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt;&lt;span style="color: #000000"&gt; EditorModelBinder : DefaultModelBinder
{    
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;protected&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;override&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&lt;span style="color: #000000"&gt; CreateModel(ControllerContext controllerContext,         
        ModelBindingContext bindingContext, Type modelType)
    {        
        &lt;/span&gt;&lt;span style="color: #0000ff"&gt;if&lt;/span&gt;&lt;span style="color: #000000"&gt; (modelType.Equals(&lt;/span&gt;&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000"&gt;(IMyObject)))
        {                
            &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get the id from the posted values&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;            var id &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; (&lt;/span&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&lt;span style="color: #000000"&gt;)controllerContext
                .RouteData
                .Values
                .GetRequiredObject(&lt;/span&gt;&lt;span style="color: #800000"&gt;"&lt;/span&gt;&lt;span style="color: #800000"&gt;id&lt;/span&gt;&lt;span style="color: #800000"&gt;"&lt;/span&gt;&lt;span style="color: #000000"&gt;);
            &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get the object from my data repository by id&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;            var model &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; GetMyObjectFromMyDataRepository(id);
            
            &lt;/span&gt;&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt;&lt;span style="color: #000000"&gt; (var p &lt;/span&gt;&lt;span style="color: #0000ff"&gt;in&lt;/span&gt;&lt;span style="color: #000000"&gt; item.Properties)
            {
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;it's the editor model that created the editor
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;for each property in mvc which means that
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;it's this data that is being posted back&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                var editorModel &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; p.DataType.EditorModel;
                
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt; ... Go convert all of the posted values using the bindingContext
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt; ValueProvider and build up the MyObject object created above
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt; ... (A bunch of code goes here to do the conversion)
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt; Except, now that it's created, how the heck do i run it through
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt; MVC validation?&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;            }
            
            &lt;/span&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt;&lt;span style="color: #000000"&gt; model;
        }

        &lt;/span&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;base&lt;/span&gt;&lt;span style="color: #000000"&gt;.CreateModel(controllerContext, bindingContext, modelType);
    }
}&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;
&lt;p&gt;In order for the call in your controller to check if your &lt;em&gt;&lt;a href="http://stackoverflow.com/questions/881281/what-is-modelstate-isvalid-valid-for-in-asp-net-mvc-in-nerddinner" target="_blank"&gt;ModelState.IsValid&lt;/a&gt;&lt;/em&gt;, something needs to do the validation of the model and put the validation results inside the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstate.aspx" target="_blank"&gt;ModelState&lt;/a&gt;&lt;em&gt;&lt;/em&gt; object. This of course already exists in the MVC framework and is done with the &lt;em&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder.aspx" target="_blank"&gt;DefaultModelBinder&lt;/a&gt;&lt;/em&gt;. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder.aspx" target="_blank"&gt;DefaultModelBinder&lt;/a&gt;&lt;em&gt; &lt;/em&gt;is pretty smart and can figure out how to automagically parse and transform the posted values into the specified model and also run it through the MVC validators so long as the model is simple enough to figure out. When your model consists of interfaces, it generally can’t do much about it because it doesn’t know how to create your interface. It also has problems when the model is complex and contains sub objects of sub objects (like the &lt;em&gt;IMyObject&lt;/em&gt;). So how do we tap in to this underlying functionality? &lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:0c165d35-45fd-4e53-b4a5-ebec5e0b4016" class="wlWriterSmartContent"&gt;&lt;pre style="background-color: white; width: 642px; height: 842px; overflow: auto"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #000000"&gt;[ModelBinderType(&lt;/span&gt;&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000"&gt;(IMyObject))]
&lt;/span&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt;&lt;span style="color: #000000"&gt; EditorModelBinder : DefaultModelBinder
{    
    &lt;/span&gt;&lt;span style="color: #0000ff"&gt;protected&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;override&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&lt;span style="color: #000000"&gt; CreateModel(ControllerContext controllerContext,         
        ModelBindingContext bindingContext, Type modelType)
    {        
        &lt;/span&gt;&lt;span style="color: #0000ff"&gt;if&lt;/span&gt;&lt;span style="color: #000000"&gt; (modelType.Equals(&lt;/span&gt;&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000"&gt;(IMyObject)))
        {                
            &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get the id from the posted values&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;            var id &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; (&lt;/span&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&lt;span style="color: #000000"&gt;)controllerContext
                .RouteData
                .Values
                .GetRequiredObject(&lt;/span&gt;&lt;span style="color: #800000"&gt;"&lt;/span&gt;&lt;span style="color: #800000"&gt;id&lt;/span&gt;&lt;span style="color: #800000"&gt;"&lt;/span&gt;&lt;span style="color: #000000"&gt;);
            &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get the object from my data repository by id&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;            var model &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; GetMyObjectFromMyDataRepository(id);
            
            &lt;/span&gt;&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt;&lt;span style="color: #000000"&gt; (var p &lt;/span&gt;&lt;span style="color: #0000ff"&gt;in&lt;/span&gt;&lt;span style="color: #000000"&gt; item.Properties)
            {
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;it's the editor model that created the editor
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;for each property in mvc which means that
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;it's this data that is being posted back&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                var editorModel &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; p.DataType.EditorModel;
                
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get a binder for the EditorModel&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                IModelBinder binder &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;&lt;span style="color: #000000"&gt;.Binders
                    .GetBinder(model.GetType());
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;create a new context for it&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                ModelBindingContext customBindingContext &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;new&lt;/span&gt;&lt;span style="color: #000000"&gt; ModelBindingContext();
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;get the meta data for it&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                customBindingContext.ModelMetadata &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; ModelMetadataProviders
                    .Current
                    .GetMetadataForType(() &lt;/span&gt;&lt;span style="color: #000000"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000"&gt; model, model.GetType());
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;ensure we use our correct field 'prefix' 
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;(this is optional and depends on if you are using a custom prefix)&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                customBindingContext.ModelName &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; p.Id.ToString();
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;use our existing model state&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                customBindingContext.ModelState &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; bindingContext.ModelState;                
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;use our existing value provider&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                customBindingContext.ValueProvider &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; bindingContext.ValueProvider;
                &lt;/span&gt;&lt;span style="color: #008000"&gt;//&lt;/span&gt;&lt;span style="color: #008000"&gt;do the binding! this will also validate and put the errors into the ModelState for us.&lt;/span&gt;&lt;span style="color: #008000"&gt;
&lt;/span&gt;&lt;span style="color: #000000"&gt;                model &lt;/span&gt;&lt;span style="color: #000000"&gt;=&lt;/span&gt;&lt;span style="color: #000000"&gt; (&lt;/span&gt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&lt;span style="color: #000000"&gt;)binder.BindModel(controllerContext, customBindingContext);
            }
            
            &lt;/span&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt;&lt;span style="color: #000000"&gt; model;
        }

        &lt;/span&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt;&lt;span style="color: #000000"&gt; &lt;/span&gt;&lt;span style="color: #0000ff"&gt;base&lt;/span&gt;&lt;span style="color: #000000"&gt;.CreateModel(controllerContext, bindingContext, modelType);
    }
}&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;
&lt;p&gt;The concept above is pretty much how a Controller’s &lt;em&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel.aspx" target="_blank"&gt;TryUpdateModel&lt;/a&gt;&lt;/em&gt; method works and how it does the underlying validation. &lt;/p&gt;</description>
      <pubDate>Thu, 23 Mar 2023 15:08:09 Z</pubDate>
      <a10:updated>2023-03-23T15:08:09Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1214</guid>
      <link>https://shazwazza.com/post/mvc-attributes-readonly-vs-editable-vs-bind-the-defaultmodelbinder/</link>
      <category>ASP.Net</category>
      <category>Umbraco</category>
      <title>MVC Attributes - ReadOnly vs Editable vs Bind &amp; the DefaultModelBinder</title>
      <description>&lt;p&gt;I’ve been learning quite a lot about the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder%28VS.90%29.aspx" target="_blank"&gt;DefaultModelBInder&lt;/a&gt; and it’s internal behaviour because of the complexities involved with some of the model binding in &lt;a href="http://umbraco.org" target="_blank"&gt;Umbraco&lt;/a&gt; v5 and wanted to point out the behaviour of the following attributes when it comes to how the DefaultModelBinder works:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.aspx" target="_blank"&gt;ReadOnly&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.editableattribute%28VS.95%29.aspx" target="_blank"&gt;Editable&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute%28VS.90%29.aspx" target="_blank"&gt;Bind&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Each of these attributes ‘seems’ like they serve the same purpose by making properties of your model read only, not-bindable, not-editable or vice versa. In my mind they all seem like they are the same but that’s just my opinion, as there could be some other hidden secret in the .Net framework which differentiates between these explicitly. The DefaultModelBinder definitely doesn’t treat each of these the same, in fact the DefaultModelBinder doesn’t check for the Editable attribute on properties. Before the DefaultModelBinder binds all of your model’s properties (If you have a complex model), it creates a new &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelbindingcontext%28VS.98%29.aspx" target="_blank"&gt;ModelBindingContext&lt;/a&gt; which contains a new &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelbindingcontext.propertyfilter%28v=VS.98%29.aspx" target="_blank"&gt;PropertyFilter&lt;/a&gt; to exclude any properties that have been defined as ReadOnly or not bindable.&lt;/p&gt;  &lt;p&gt;There’s a few internal/private methods of the DefaultModelBinder that do these lookups:&lt;/p&gt;  &lt;p&gt;This one creates the new model binding context and checks if any BindAttributes have been declared for the model, if so, then it creates a new property filter which combines the BindAttribute filter and the standard model binder filter:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:d5af5bc0-bd08-433a-a14d-54ddc238e97f" class="wlWriterEditableSmartContent"&gt;&lt;pre style=" width: 650px; height: 284px;background-color:White;overflow: auto;"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000FF;"&gt;internal&lt;/span&gt;&lt;span style="color: #000000;"&gt; ModelBindingContext CreateComplexElementalModelBindingContext(ControllerContext controllerContext, ModelBindingContext bindingContext, &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;object&lt;/span&gt;&lt;span style="color: #000000;"&gt; model) {
    BindAttribute bindAttr &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; (BindAttribute)GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000;"&gt;(BindAttribute)];
    Predicate&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;string&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; newPropertyFilter &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; (bindAttr &lt;/span&gt;&lt;span style="color: #000000;"&gt;!=&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;null&lt;/span&gt;&lt;span style="color: #000000;"&gt;)
        &lt;/span&gt;&lt;span style="color: #000000;"&gt;?&lt;/span&gt;&lt;span style="color: #000000;"&gt; propertyName &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindAttr.IsPropertyAllowed(propertyName) &lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindingContext.PropertyFilter(propertyName)
        : bindingContext.PropertyFilter;

    ModelBindingContext newBindingContext &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;new&lt;/span&gt;&lt;span style="color: #000000;"&gt; ModelBindingContext() {
        ModelMetadata &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; ModelMetadataProviders.Current.GetMetadataForType(() &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; model, bindingContext.ModelType),
        ModelName &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindingContext.ModelName,
        ModelState &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindingContext.ModelState,
        PropertyFilter &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; newPropertyFilter,
        ValueProvider &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindingContext.ValueProvider
    };

    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;return&lt;/span&gt;&lt;span style="color: #000000;"&gt; newBindingContext;
}
&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p&gt;This method is called to do the actual binding of each property, but as you can see it only binds properties that have been filtered:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:10f6d841-5830-401f-bf28-d279d9165728" class="wlWriterEditableSmartContent"&gt;&lt;pre style=" width: 650px; height: 113px;background-color:White;overflow: auto;"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000FF;"&gt;private&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;void&lt;/span&gt;&lt;span style="color: #000000;"&gt; BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {
    IEnumerable&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;PropertyDescriptor&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; properties &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; GetFilteredModelProperties(controllerContext, bindingContext);
    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;foreach&lt;/span&gt;&lt;span style="color: #000000;"&gt; (PropertyDescriptor property &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;in&lt;/span&gt;&lt;span style="color: #000000;"&gt; properties) {
        BindProperty(controllerContext, bindingContext, property);
    }
}
&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p&gt;The GetFilteredModelProperties method gets all of the unfiltered &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.aspx" target="_blank"&gt;PropertyDescriptor&lt;/a&gt;’s of the model, and then calls ShouldUpdateProperty to perform the actual filtering (which passes in the new ModelBindingContext’s PropertyFilter which is now based on the Bind attribute if one was declared on the model):&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:ce316a48-d796-4648-815d-8fa0555a05c2" class="wlWriterEditableSmartContent"&gt;&lt;pre style=" width: 650px; height: 161px;background-color:White;overflow: auto;"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000FF;"&gt;protected&lt;/span&gt;&lt;span style="color: #000000;"&gt; IEnumerable&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;PropertyDescriptor&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; GetFilteredModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {
    PropertyDescriptorCollection properties &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; GetModelProperties(controllerContext, bindingContext);
    Predicate&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;string&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; propertyFilter &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; bindingContext.PropertyFilter;

    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;return&lt;/span&gt;&lt;span style="color: #000000;"&gt; from PropertyDescriptor property &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;in&lt;/span&gt;&lt;span style="color: #000000;"&gt; properties
           &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;where&lt;/span&gt;&lt;span style="color: #000000;"&gt; ShouldUpdateProperty(property, propertyFilter)
           select property;
}&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p&gt;The ShouldUpdateProperty method does the following:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Check if the PropertyDescriptor is read only. This is determined by whether or not the ReadOnly attribute was specified on the model property, &lt;em&gt;the Editable attribute doesn’t seem to affect this value&lt;/em&gt;. The first check also makes a call to CanUpdateReadonlyTypedReference which checks for value types such as guid, int, string, and ensures they are excluded if IsReadOnly is true. &lt;/li&gt;

  &lt;li&gt;Check if the property filter allows the property to be bound which is based on the Bind attribute (if supplied on the model) &lt;/li&gt;
&lt;/ol&gt;



&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:6087e244-f8f0-4c47-b538-109f768cdf7a" class="wlWriterEditableSmartContent"&gt;&lt;pre style=" width: 650px; height: 229px;background-color:White;overflow: auto;"&gt;&lt;div&gt;&lt;!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt;&lt;span style="color: #0000FF;"&gt;private&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;static&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;bool&lt;/span&gt;&lt;span style="color: #000000;"&gt; ShouldUpdateProperty(PropertyDescriptor property, Predicate&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;string&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt; propertyFilter) {
    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;if&lt;/span&gt;&lt;span style="color: #000000;"&gt; (property.IsReadOnly &lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #000000;"&gt;!&lt;/span&gt;&lt;span style="color: #000000;"&gt;CanUpdateReadonlyTypedReference(property.PropertyType)) {
        &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;return&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;false&lt;/span&gt;&lt;span style="color: #000000;"&gt;;
    }

    &lt;/span&gt;&lt;span style="color: #008000;"&gt;//&lt;/span&gt;&lt;span style="color: #008000;"&gt; if this property is rejected by the filter, move on&lt;/span&gt;&lt;span style="color: #008000;"&gt;
&lt;/span&gt;&lt;span style="color: #000000;"&gt;    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;if&lt;/span&gt;&lt;span style="color: #000000;"&gt; (&lt;/span&gt;&lt;span style="color: #000000;"&gt;!&lt;/span&gt;&lt;span style="color: #000000;"&gt;propertyFilter(property.Name)) {
        &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;return&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;false&lt;/span&gt;&lt;span style="color: #000000;"&gt;;
    }

    &lt;/span&gt;&lt;span style="color: #008000;"&gt;//&lt;/span&gt;&lt;span style="color: #008000;"&gt; otherwise, allow&lt;/span&gt;&lt;span style="color: #008000;"&gt;
&lt;/span&gt;&lt;span style="color: #000000;"&gt;    &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;return&lt;/span&gt;&lt;span style="color: #000000;"&gt; &lt;/span&gt;&lt;span style="color: #0000FF;"&gt;true&lt;/span&gt;&lt;span style="color: #000000;"&gt;;
}
&lt;/span&gt;&lt;/div&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;



&lt;p&gt;So the result of what can actually be bound in the DefaultModelBinder is:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Any property that doesn’t have &lt;em&gt;[ReadOnly(true)] &lt;/em&gt;specified &lt;/li&gt;

  &lt;li&gt;Any property that is referenced as an &lt;em&gt;Include&lt;/em&gt; using the Bind attribute on the model containing the property: 

    &lt;ul&gt;
      &lt;li&gt;[Bind(Include = “MyProperty”)] &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Any property that is NOT referenced as an &lt;em&gt;Exclude &lt;/em&gt;using the Bind attribute on the model containing the property: 

    &lt;ul&gt;
      &lt;li&gt;[Bind(Exclude = “NotThisProperty”)] &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So it appears that even if you set the an editable attribute as [Editable(false)], this property will still be included for binding.&lt;/p&gt;

&lt;p&gt;The DefaultModelBinder is quite a crazy beast and contains a lot of functionality under the hood. What I’ve mentioned above is based purely on experience and looking at the source code so if you have any feedback or feel that any of this is in error please comment!&lt;/p&gt;</description>
      <pubDate>Thu, 23 Mar 2023 15:08:09 Z</pubDate>
      <a10:updated>2023-03-23T15:08:09Z</a10:updated>
    </item>
  </channel>
</rss>