Asp.net

ASP.net MVC v2 - 調試模型綁定問題 - BUG?

  • November 4, 2009

我在嘗試調試為什麼 MVC 在給定情況下無法正確綁定時遇到了很多困難…

基本上,我的動作接收一個複雜對象,該對象又具有一個複雜的子對象 - Activity.Location.State (其中 Activity 是動作期望的複雜對象, Location 是一個複雜的子對象,而 State 只是一個字元串) .

現在我建立了一個測試項目,據我所知,它完全模仿了我所擁有的實際場景,在這個測試案例中,綁定有效……但在我的實際項目中,綁定到 Activity 有效,但不綁定到 Location……通過在 Locaiton 屬性中放置斷點,我可以看出 MVC 正在從 Activity 中檢索複雜的 Location 對象,但它沒有設置任何屬性……

我正在嘗試調試該問題,但我需要訪問我似乎無法追踪的 MVC v2 preview 2 符號……我想看看它在拉出位置對像後實際在做什麼(對於某些原因我認為它可能會在內部失敗但會吞下異常)。

關於我可以在這裡做什麼的任何想法……

乾杯安東尼

更新:

好的,我按照 JW 的建議做了,直接引用了 MVC 項目……

我發現了這個問題,並且我忽略了一個非常小的差異……結果我發現 MVC 目前在模型綁定方面不支持多級 INTERFACE 繼承……請參閱以下內容……

//MODEL
public class Location : ILocation
{
   ...
}

public interface ILocation : ILocationCore
{
   ...
}

public interface ILocationCore    //In my sample I didn't have this second level interface
{
   ...
   //MVC doesn't find any of these properties
   ...
}


public class Activity : IActivity
{
   ...
}

public interface IActivity : IActivityCore
{
   ILocation Location { get; set; }   //MVC finds this and reads its meta type as an ILocation
   //Also the implementation of this Location within Activity will always return a instance - our IoC takes care of that, so MVC should never have to create the instance
}

public interface IActivityCore
{
   ...
}

//CONTROLLER
public ActionResult Create(Activity activity)
{
}

因此,我發現 MVC 找到 Location 並將其元類型讀取為 ILocation,但是當 GetModelProperties 在 DefaultModelBinder 中執行時,會發生以下情況 -

   protected virtual PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {
       return GetTypeDescriptor(controllerContext, bindingContext).GetProperties();
       //This return no properties
   }

   protected virtual ICustomTypeDescriptor GetTypeDescriptor(ControllerContext controllerContext, ModelBindingContext bindingContext) {
       return new AssociatedMetadataTypeTypeDescriptionProvider(bindingContext.ModelType).GetTypeDescriptor(bindingContext.ModelType);
       //bindingContext.ModelType - is ILocation
   }

因此,我現在假設 TypeDescriptionProvider 不支持這種繼承方式,對此我感到非常驚訝。還查看 v1 原始碼,它看起來像是 v2 引入的 - 但 v1 可能無法支持我正在嘗試做的事情。

我不會說這真的是一個錯誤,但我嘗試用具體的類替換我的介面並且它工作得很好。因此,這種行為並不是我所期望的,而且有點不一致。

有什麼想法嗎???我會認為這種繼承不是相當標準,但會經常發生,足以滿足要求。謝謝回复。

乾杯

事實證明,由於介面繼承的工作原理,這種行為是設計使然。介面不定義實現,因此 ILocation 不會“繼承” ILocationSource 的屬性。相反,ILocation 只定義了具體實現必須實現的內容。

有關完整的詳細資訊,包括定義此行為的 CLI(通用語言基礎結構)規範部分,請查看:http ://haacked.com/archive/2009/11/10/interface-inheritance-esoterica.aspx

引用自:https://stackoverflow.com/questions/1676731