views:

586

answers:

3

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_142.MoveNext() +273 System.Web.Mvc.&lt;Validate&gt;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 Rolling_Razor_MVC.Controllers.CompanyController.ContactUsForm(FormCollection formData) in R:\WEBSITES\ROLLINGRAZOR.COM - MVC\Rolling Razor MVC\Controllers\CompanyController.cs:158 lambda_method(ExecutionScope , ControllerBase , Object[] ) +86 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +178 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +24 System.Web.Mvc.&lt;&gt;c__DisplayClassd.&lt;InvokeActionMethodWithFilters&gt;b__a() +52 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +254 System.Web.Mvc.<>c_DisplayClassf.<InvokeActionMethodWithFilters>b_c() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +254 System.Web.Mvc.&lt;&gt;c__DisplayClassf.&lt;InvokeActionMethodWithFilters&gt;b__c() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +254 System.Web.Mvc.<>c_DisplayClassf.<InvokeActionMethodWithFilters>b_c() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +192 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<>c_DisplayClass8.<BeginProcessRequest>b_4() +34 System.Web.Mvc.Async.<>c_DisplayClass1.<MakeVoidDelegate>b_0() +21 System.Web.Mvc.Async.<>c__DisplayClass81.&lt;BeginSynchronous&gt;b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8679134 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: 

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.

Simon_Weaver
+2  A: 

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!

SevenCentral
Check the answer to the above post.
SevenCentral
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 good
Simon_Weaver
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.
Erx_VB.NExT.Coder
A: 

I HAVE THE EXACT SAME PROBLEM!!

For more information about my issue, you may visit http://stackoverflow.com/questions/2766291/asp-net-mvc-2-0-unused-model-property-being-called-when-posting-a-product-to-the

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.

Erx_VB.NExT.Coder
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 MVC3
Simon_Weaver