数据绑定过程中为什么我的ASP.NET MVC护理只读属性? [英] Why does ASP.NET MVC care about my read only properties during databinding?

查看:139
本文介绍了数据绑定过程中为什么我的ASP.NET MVC护理只读属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改:增加了赏金,因为我寻求一个解决MVC3(如果存在),除此以外的:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = FALSE;


我有一个只读属性在我的地址模型'CityStateZip

这只是一个方便的方式来获得市,州,从美国地址邮编。如果国家不在美国(主叫方应该先检查一下)。

它抛出一个异常

 公共字符串CityStateZip
    {
        得到
        {
            如果(IsUSA == FALSE)
            {
                抛出新ApplicationException的(CityStateZip不适用于国际地址!);
            }            回报(市+,+ StateCd ++ ZipOrPostal).Trim()修剪(新的char [] {','});
        }
    }

这是我的模型的一部分​​,所以它得到约束。此前ASP.NET MVC2 RC2这一领域从未绑定过程中造成的问题。我从来没有真正想过这个问题 - 毕竟它只是只读

现在虽与2010年1月RC2发布它给了我绑定过程中发生错误 - becasue默认模型绑定似乎要检查该值(即使它是只读)

据被触发导致该错误base.OnModelUpdated行。

 公共类AddressModelBinder:DefaultModelBinder
{
    保护覆盖无效OnModelUpdated(ControllerContext controllerContext,ModelBindingContext的BindingContext)
    {
        base.OnModelUpdated(controllerContext,BindingContext中);

到ModelBinder的

最后几分钟的变化显然引起的这种行​​为改变 - 但我不能肯定是什么还没有它的repurcussions是 - 或者是否这是不是一个错误?我通过这个到MVC的球队,但好奇,如果任何人有在此期间的任何建议,我怎么能prevent这个属性的结合。

这篇文章很值得一读有关的变化 - 但没有提到在所有的只读属性(不,我希望它)。这个问题(如果有的话)可能比这个更广泛的情况 - 我只是不知道任何repurcussions - 如果有的话

<一个href=\"http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html\">Input验证与模型验证在ASP.NET MVC


作为的要求在这里@haacked的堆栈跟踪:

我通过简单地添加以下行任何模型,使一个岗位相应的操作方法来获取此。在这种情况下我把它添加到我的最简单的可能模式。

 公共字符串美孚{获得{抛出新的异常(巴); }}


  

[TargetInvocationException:属性访问器'富'的对象'Rolling_Razor_MVC.Models.ContactUsModel抛出以下异常:'酒吧']
     System.ComponentModel.ReflectPropertyDescriptor.GetValue(对象组件)+390
     System.Web.Mvc&LT;&GT; C_的 DisplayClassb&LT; GetPropertyValueAccessor&GT; b 的_a()+18
     System.Web.Mvc.ModelMetadata.get_Model()+22
     System.Web.Mvc.ModelMetadata.get_RealModelType()+29
     System.Web.Mvc&LT; GetValidatorsImpl&GT; D_的 0.MoveNext()+38
     System.Linq的&LT; SelectManyIterator D 1和D
的_14`2.MoveNext()+ 273
     System.Web.Mvc&LT;&验证GT; d__5.MoveNext()644
     System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext,ModelBindingContext的BindingContext)+92
     System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext,ModelBindingContext的BindingContext,对象模型)+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模型,字符串preFIX,字符串[] includeProperties,字符串[] excludeProperties,IValueProvider valueProvider)449
     System.Web.Mvc.Controller.TryUpdateModel(模型的TModel)+73



解决方案

我相信我遇到类似的问题。我已经张贴了详细介绍:

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


修改:从响应团队的MVC(从上面的网址):

我们调查了这一点,得出的结论是预期验证系统的行为。由于模型验证包括试图在所有性能运行审定,因为非空值类型属性都有一个隐含的[必需]属性,我们要验证此属性,并调用它在这个过程中吸气。据我们了解,这是从产品的V1重大更改,但它是必要的,使新的模型验证系统的正常工作。

您有几种选择来解决这个问题。其中任何一个应该工作:


  • 更改日期属性的方法,而不是一个属性;这种方式,将被MVC框架被忽略。

  • 更改属性类型为DateTime?而不是日期时间。这从该属性中删除隐[必填]。

  • 清除静态DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes标志。这将删除所有非空值类型属性隐[必填]的应用范围。
    我们正在考虑增加在其中将信号给我们一个属性的产品V3不绑定,不对其进行验证,只需pretend这个属性不存在。

有关报告再次感谢!

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

解决方案

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!

这篇关于数据绑定过程中为什么我的ASP.NET MVC护理只读属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆