c# .net Request.Param
i think i know the answer to this question, bu开发者_如何学编程t it never hurts to ask...
our .net application needs to store things like names in the database. we just discovered some fields with leading spaces.
1) i could go thru every single field we store in the database and trim each value before it goes in. but i really would like to avoid having to do that and forgetting the next time a field is added.
2) another way would be to trim all the request params before they are processed into objects in my controller action parameter list. this seems cleanest to me because it would cover any eventuality. however it looks like the request parameters are read only at run time, even though if i write code, the compiler is happy to let me put a param on the lhs.
3) finally, i could trim all the values before they are transmitted to the server. i can do this very easily b/c i'm using extjs and can add a global 'getRawValue()' that trims the string when extracting it from a form field. this is less appealing, more on philosophical grounds: the front end should not have to perform tasks to ensure the database is in good shape.
--
it looks like (3) is the best option (for me). comments?
It sounds like you're using MVC. You could use a custom model binder that trims string values when binding the parameters to your action parameters.
The model binder is the service that transforms the Request parameters into actual objects that get passed into your controller actions. See this link for a good explanation.
While I haven't done this myself, it appears that something like this ought to work:
public class MyModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
var valString = value as string;
if(valString != null)
{
value = valString.Trim();
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
You basically just override the default behavior to trim any string value before setting it as the value of an action parameter or a property on an action's parameter.
I haven't figured out how to register this as your default model binder with ASP.NET MVC: that may actually depend on your IoC container.
精彩评论