问题描述
如何在绑定到模型之前拦截提交的表单输入并对其进行修改?例如,如果我想修剪所有文本的空白.
How can I intercept submitted form input and modify it before it is bound to my model? For example, if I wanted to trim the whitespace from all text.
我尝试过像这样创建自定义模型联编程序:
I have tried creating a custom model binder like so:
public class CustomBinder : DefaultModelBinder {
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {
string newValue = ((string)value).Trim(); //example code to create new value but could be anything
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, newValue);
}
}
,但这似乎没有被调用.有没有更好的地方可以修改输入值?
but this doesn't seem to be invoked. Is there a better place to modify the input value?
注意:我需要在绑定和验证该值之前对其进行修改.
Note: I need to modify the value before it is bound and validated.
推荐答案
您确定使用模型绑定程序吗?例如.可以通过在Application_Start
中执行以下操作来替换默认的模型联编程序:
Did you make sure that your model binder was used? E.g. the default model binder can be replaced by doing this in Application_Start
:
ModelBinders.Binders.DefaultBinder = new MyVeryOwnModelBinder();
我已经成功完成了多次,对POST数组进行了重新索引操作.
I have successfully done this multiple times, applying a re-indexing operation to a POST'ed array.
我通过覆盖BindModel
方法,在bindingContext.ValueProvider
词典中查找发布的值来进行重新索引.
I did the re-indexing by overriding the BindModel
method, looking up posted values in the bindingContext.ValueProvider
dictionary.
应该可以仅编辑此字典,以便在模型绑定之前修改POST的值.
It should be possible to just edit this dictionary in order to modify the POST'ed values before model binding.
这篇关于在ASP.NET MVC中进行模型绑定之前,如何修改输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!