簡體   English   中英

PropertyDescriptor.SetValue 在 ModelBinder 中不起作用

[英]PropertyDescriptor.SetValue not working in ModelBinder

我正在實現一個自定義ModelBinder ,我正在嘗試使用PropertyDescriptor.SetValue設置一個屬性,但我無法弄清楚它為什么不起作用。

對於一些復雜的屬性,該值沒有被設置,但它不會引發異常。 該屬性仍然是null但對於某些人來說確實如此。

如果我檢索一個PropertyInfo並調用SetValue它每次都可以正常工作。

來自 codeplex 的 Mvc 源正在使用propertyDescriptor.SetValue(bindingContext.Model, value); 在內部所以我猜這是 go 的最佳方式?

public class MyCustomBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(bindingContext.Model))
            {
                object value = property.GetValue(bindingContext.Model);
                // Perform custom bindings

                // Call SetValue on PropertyDescriptor (Works sometimes)
                property.SetValue(bindingContext.Model, value);
                Debug.Assert(property.GetValue(bindingContext.Model) == value, "Value not set");

                // Get PropertyInfo and call SetValue (Working)                    
                bindingContext.ModelType.GetProperty(property.Name).SetValue(bindingContext.Model, value, null);
                Debug.Assert(property.GetValue(bindingContext.Model) == value, "Value not set");
            }
            return bindingContext.Model;
        }
    }

注 1:我反映的對象是用 nhibernate 映射的,所以我懷疑代理可能有問題。

注意 2:它也不適用於 DefaultModelBinder,但正在重新創建對象,因此發布的數據很好。

我不確定你想要實現什么,但如果你已經知道 propertyInfo.setValue 給了你想要的東西,我會忽略 MVC 源代碼使用 propertyDescriptor.SetValue 的事實。 您正在編寫擴展 class,只需使用有效且良好的代碼即可:

Type modelType = bindingContext.ModelType;
foreach (PropertyInfo property in modelType.GetProperties())
{
    // ...
    property.SetValue(bindingContext.Model, value, null);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM