我已經寫了自定義的模型綁定,使用ASP.NET MVC 2.本模型綁定綁定僅有2模型的領域:單元測試定製的模型綁定2
public class TaskFormBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "Type")
{
var value = bindingContext.ValueProvider.GetValue("Type");
var typeId = value.ConvertTo(typeof(int));
TaskType foundedType;
using (var nhSession = Domain.GetSession())
{
foundedType = nhSession.Get<TaskType>(typeId);
}
if (foundedType != null)
{
SetProperty(controllerContext, bindingContext, propertyDescriptor, foundedType);
}
else
{
AddModelBindError(bindingContext, propertyDescriptor);
}
return;
}
if (propertyDescriptor.Name == "Priority")
{ /* Other field binding ... */
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
如何我可以使用標準VS單元測試來測試此模型活頁夾嗎?花了一些小時Google搜索,找到幾個例子(http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx),但這個例子是爲MVC1,並且在使用MVC2時不工作。
我感謝您的幫助。
你的回答讓我從MVC源代碼中解脫出來。我試圖做同樣的更新,並得出幾乎相同的結果。不幸的是,我沒有在'ModelBindingContext'上設置'ModelMetaData'。沒有它,你會在'BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)'上得到一個不起眼的'NullReferenceException'。 – patridge 2010-05-12 21:06:13
謝謝你。它很好地爲我清理了一些東西。 – 2010-12-09 19:40:47
我正要創建一個自定義的ValueProvider,但是要感謝你提到的NameValueCollectionValueProvider。這很有用。謝謝。 – Mani 2011-03-25 10:04:58