我知道ModelBinder是一個很好的地方可以處理請求,這樣您就可以將這種類型的代碼保留在控制器之外。使用表單值將是一個例子。這似乎是有道理的,但是,我繼承了一個使用自定義活頁夾的應用程序,我似乎無法弄清楚它是如何工作的或爲什麼工作的。我不是在MVC中「獲取」ModelBinder 2
粘合劑本身的存在是爲了對付他們(時區)的應用程序中使用,因此它在Application_Start方法進行註冊,在全球,像這樣只的TimeZoneInfo對象:
binders.Add(new System.Collections.Generic.KeyValuePair<Type, IModelBinder>(typeof(TimeZoneInfo), new TimeZoneInfoModelBinder()));
其中粘合劑是鍵入ModelBinderDictionary。該粘合劑本身則是這樣的:
public class TimeZoneInfoModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
string tzId = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
try
{
return TimeZoneInfo.FindSystemTimeZoneById(tzId);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
}
return null;
}
}
現在從單步調試代碼我知道當我POST數據回涉及其上有一個的TimeZoneInfo屬性的特定型號的服務器此Binder只調用。我的假設是:
- 運行時「知道」所有的模型,只調用自定義粘結劑時,它會發現相同的類型在該粘結劑通過一個屬性。
- 這個正在做的原因是因爲所述的TimeZoneInfo類型是一個複雜的類型,因此,不能隱從字符串轉換爲(POST數據)
這是這個特定的正確認識實例還是我錯過了什麼?
謝謝!
感謝您的解釋羅布。 – dparsons 2010-07-20 17:06:37