3
我需要在MVC2中的POST數據綁定之前過濾掉一些值。不幸的是,我不能改變客戶端代碼,它有時會傳遞「N/A」來映射到十進制的表單值嗎?類型。需要發生的是如果「N/A」是POST值在綁定/驗證之前將其空白。使用MVC ModelBinders在綁定之前過濾帖子值
我已經嘗試了所有上午得到它的工作使用擴展DefaultModelBinder一個模型綁定器:
public class DecimalFilterBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(decimal?))
{
var model = bindingContext.Model;
PropertyInfo property = model.GetType().GetProperty(propertyDescriptor.Name);
var httpRequest = controllerContext.RequestContext.HttpContext.Request;
if (httpRequest.Form[propertyDescriptor.Name] == "-" ||
httpRequest.Form[propertyDescriptor.Name] == "N/A")
{
property.SetValue(model, null, null);
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
我遇到的問題是我不知道怎麼去訪問最初發布值當它在一個列表中時。我不能只是爲了Form[propertyDescriptor.Name]
,因爲它包含在表單中的列表項中(例如,輸入真的是Values[0].Property1
)。我有模型聯編程序掛在global.asax並運行良好,我只是不知道如何獲得原始表單值的過濾,以在默認綁定發生之前將其過濾爲空字符串。