Why does ASP.NET MVC care about my read only properties during databinding?
Asked Answered
M

7

22

Edit: Added bounty because I'm seeking an MVC3 solution (if one exists) other than this:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;


I have a read only property on my 'Address' model 'CityStateZip'.

It's just a convenient way to get city, state, zip from a US address. It throws an exception if the country is not USA (the caller is supposed to check first).

    public string CityStateZip
    {
        get
        {
            if (IsUSA == false)
            {
                throw new ApplicationException("CityStateZip not valid for international addresses!");
            }

            return (City + ", " + StateCd + " " + ZipOrPostal).Trim().Trim(new char[] {','});
        }
    }

This is part of my model so it gets bound. Prior to ASP.NET MVC2 RC2 this field never caused a problem during databinding. I never even really thought about it - after all it is only read only.

Now though with the January 2010 RC2 release it gives me an error during databinding - becasue the default model binder seems to want to check this value (even though it is read only).

It is the 'base.OnModelUpdated' line that causes this error to be triggered.

public class AddressModelBinder : DefaultModelBinder
{
    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        base.OnModelUpdated(controllerContext, bindingContext);

Last minutes changes to the modelbinder evidently caused this change in behavior - but I'm not quite sure yet what the repurcussions of it are - or whether or not this is a bug? I'm passing this on to the MVC team but curious if anyone else has any suggestions in the meantime how I can prevent this property from binding.

This article is well worth reading about the changes - but doesn't mention readonly properties at all (not that I would expect it to). The issue (if there is one) may be broader than this situation - I'm just not sure about any repurcussions - if any!

Input Validation vs. Model Validation in ASP.NET MVC


As requested by @haacked here's the stacktrace :

I get this by simply adding the following line to ANY model and making a post to the corresponding action method. In this instance I added it to my simplest possible model.

 public string Foo { get { throw new Exception("bar"); } }

[TargetInvocationException: Property accessor 'Foo' on object 'Rolling_Razor_MVC.Models.ContactUsModel' threw the following exception:'bar'] System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +390 System.Web.Mvc.<>c__DisplayClassb.<GetPropertyValueAccessor>b__a() +18 System.Web.Mvc.ModelMetadata.get_Model() +22 System.Web.Mvc.ModelMetadata.get_RealModelType() +29 System.Web.Mvc.<GetValidatorsImpl>d__0.MoveNext() +38 System.Linq.<SelectManyIterator>d__14`2.MoveNext() +273 System.Web.Mvc.<Validate>d__5.MoveNext() +644 System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +92 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +60 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 System.Web.Mvc.Controller.TryUpdateModel(TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider) +449 System.Web.Mvc.Controller.TryUpdateModel(TModel model) +73

Mcnalley answered 6/2, 2010 at 2:59 Comment(7)
What is the exact error you're seeing? It would also be helpful to see the relevant controller and view code.Edelstein
We need more detail, but my guess is IsUsa is false when we try to read that property, which causes an exception to be thrown. Not sure why we would be reading it during model binding though, unless there's a form field named "CityStateZip" in the form that's being posted.Thevenot
@brad well the exact error is 'CityStateZip not valid for international addresses!' ;-) i'm updating the question with the full stack trace. to duplicate just add this to ANY existing model you have and make a POST to the corresponding actionmethod: public string Foo { get { throw new Exception("bar"); } }Mcnalley
@haacked - right thats the point. its definitely becuase IsUSA is false - but for me its just a safeguard to make sure I never attempt to display CityStateZip for a non US address. you never looked at it before - but now you are. thats why I wanted to raise it as a possible issue. for me its trivial to fix (see my answer below) but to others it could unnecessarily be a big headache. who knows! thanks!Mcnalley
Based on the stack trace, it looks like the problem is because we're trying to find validators for the property, which means we need to know what it's actual type is, which means querying the value. A throw here was unexpected, which we'll need to guard against.Edelstein
@brad one additional situation i've had is where my model has certain properties injected into it by [Attributes] and there are deliberate throw clauses to prevent trying to access those properties during the lifetime of the controller (when they haven't yet been set). these failed with the new change - but again was an easy workaround. thx for the info and looking into thisMcnalley
I HAVE THE EXACT SAME PROBLEM!! to read mine, please take a look at #2766791 this is certainly based on the same issueHawks
I
19

I believe I'm experiencing a similar issue. I've posted the details:

http://forums.asp.net/t/1523362.aspx


edit: Response from MVC team (from above URL):

We investigated this and have concluded that the validation system is behaving as expected. Since model validation involves attempting to run validation over all properties, and since non-nullable value type properties have an implicit [Required] attribute, we're validating this property and calling its getter in the process. We understand that this is a breaking change from V1 of the product, but it's necessary to make the new model validation system operate correctly.

You have a few options to work around this. Any one of these should work:

  • Change the Date property to a method instead of a property; this way it will be ignored by the MVC framework.
  • Change the property type to DateTime? instead of DateTime. This removes the implicit [Required] from this property.
  • Clear the static DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes flag. This removes the implicit [Required] from all non-nullable value type properties application-wide. We're considering adding in V3 of the product an attribute which will signal to us "don't bind it, don't validate it, just pretend that this property doesn't exist."

Thanks again for the report!

Inconformity answered 8/2, 2010 at 20:32 Comment(3)
Check the answer to the above post.Inconformity
two things this doesn't address is the fact that my property was read only so it shouldn't ever need to be 'got'. so this solution slightly screws up my design, but the workarounds still work. the second thing is that this blows up with an exception anyway. thats definitely not good. if the model fails the model fails but blowing up is not goodMcnalley
i'm having the exact same problem, please read my reply post with link if you like. i am eagerly awaiting mvc v3 as there are just too many unresolved/missing elements in v2, including this and ability to return multiple views to update different physical areas of a webpage, better custom server-side validation support, etc etc... can get around these issues at the moment, but only so by using 'hacks' and i don't feel the elegance of coding that i should feel using mvc ;( - i cannot wait for v3.Hawks
M
2

Still having the same issue with MVC3.

I think the best way is to just to this in global.asax (from SevenCentral's answer):

 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

This will disable for all of them

Mcnalley answered 4/5, 2011 at 1:0 Comment(0)
W
1

This looks for all the world like a bug to me. I fully can't understand why the ModelBinder needs to check my read only properties (there may be some technicalities, but I definitely don't understand, and am not willing to spend the time trying to).

I added the following Model Meta Data Provider in to my solution to get round the problem

protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
{
    var metadata = base.CreateMetadataPrototype(attributes, containerType, modelType, propertyName);

    if (metadata.IsReadOnly)
    {
        metadata.IsRequired = false;
    }

    return metadata;
}

protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
{
    var metadata = base.CreateMetadataFromPrototype(prototype, modelAccessor);

    if (prototype.IsReadOnly)
    {
        metadata.IsRequired = false;
    }

    return metadata;
}

You will also need to add the following to Global.asax.cs

protected void Application_Start()
{
    ModelMetadataProviders.Current = new RESModelMetadataProvider();
    ModelBinders.Binders.Add(typeof(SmartDate), new SmartDateModelBinder());

    ...
}
Wormeaten answered 14/3, 2014 at 16:53 Comment(1)
Awesome, this should be the accepted answer: totally solves the problem at the source. Newer versions of MVC have different method names: GetMetadataForProperty. VS can automatically create the stubs if you type protected override, then just add the if statements.Locate
M
0

Of course I guess I could convert CityStateZip to GetCityStateZip() but then I cant bind it in something like silverlight quite as easily. This might work for a temporary fix for anyone else experiencing this issue.

Mcnalley answered 6/2, 2010 at 3:6 Comment(0)
H
0

I HAVE THE EXACT SAME PROBLEM!!

For more information about my issue, you may visit ASP.NET MVC 2.0 Unused Model Property being called when posting a product to the server?

does this mean we need to program our properties with the assumption that they'll be called unexpectedly (before properties which it depends on are set up/initialized etc)... if so, this represents a change in our programming practices and i would like to know how to proceed.

meanwhile, i just have a simple 'if' check that rids the problem.

Hawks answered 6/5, 2010 at 13:18 Comment(1)
generally properties are meant to be just that - dumb properties. if you have too much business logic in there then yes you'll have to make a change, but you perhaps ought to anyway. its a shame they couldnt add some kind of 'dont validate' property but perhaps that will come for MVC3Mcnalley
C
0

I was having a similar problem, a field which I did not expect to be validated was receiving an error when the form posted back to the controller. After some googling, I came across http://codeblog.shawson.co.uk/mvc-strongly-typed-view-returns-a-null-model-on-post-back/ where it was pointed out that name conflicts could cause problems.

Though I did not think my post-back variable class had conflicting property names, renaming the property receiving the error solved my problem.

Concavity answered 10/5, 2012 at 14:51 Comment(0)
C
0

The same problem still exists in MVC 5.2.3, and it isn't even the validation code causing the problem. The DefaultModelBinder calls the getters outside of its validation code even if they are read-only properties and even if no request data is being passed to the controller matching those properties.

See a more detailed explanation and my full solution here: https://mcmap.net/q/589181/-why-is-getter-being-called.

I'm not sure if that solution can be refactored to work with MVC 3, but hopefully it can help others still suffering from the same issue in the later version of MVC that stumbled across this question as I did.

Commutator answered 30/1, 2019 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.