我已经写了自定义的模型绑定,使用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