Tôi đã viết binder mô hình tùy chỉnh trong dự án, sử dụng ASP.NET MVC 2. model binder này ràng buộc chỉ 2 lĩnh vực mô hình:Unit mô hình thử nghiệm tùy chỉnh chất kết dính trong ASP.NET MVC 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);
}
}
thế nào tôi có thể kiểm tra chất kết dính mô hình này bằng cách sử dụng thử nghiệm đơn vị VS standart? Dành một vài giờ googling, tìm vài ví dụ (http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx), nhưng ví dụ này là dành cho MVC1, và không làm việc khi sử dụng MVC2.
Tôi đánh giá cao sự trợ giúp của bạn.
Câu trả lời của bạn đã cứu tôi khỏi việc nhét xung quanh trong nguồn MVC. Tôi đã cố gắng thực hiện cập nhật tương tự và đưa ra kết quả tương tự. Thật không may, tôi đã không thiết lập 'ModelMetaData' trên' ModelBindingContext'. Nếu không có nó, bạn sẽ nhận được một NullReferenceException' không xác định trên 'BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)'. – patridge
Cảm ơn vì điều này. Nó xóa một số điều cho tôi độc đáo. –
Tôi sắp tạo một ValueProvider tùy chỉnh, nhưng nhờ NameValueCollectionValueProvider mà bạn đã đề cập. Điều này rất hữu ích. Cảm ơn. – Mani