用一个例子更容易解释。假设我有一个人类
Public Person
{
string firstName;
string SocialSecurityNumber;
}
当用户在网页中进行某些更改时,Person 对象将被发送回接受 Person 作为输入参数的 Controller 。社会安全号码已加密。我们有许多页面回发对象(不一定是 Person 类),这些对象已加密的社会保障作为参数。现在我想修改模型绑定(bind),以便如果发布的对象具有 SocialSecurityNumber 作为属性,则应该自动解密。我怎样才能做到这一点?
最佳答案
您可以使用自定义模型绑定(bind)器。一些例子:
- http://www.dotnetcurry.com/ShowArticle.aspx?ID=584
- http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx
- http://www.markeverard.com/blog/2011/07/18/creating-a-custom-modelbinder-allowing-validation-of-injected-composite-models/
这是我之前使用过的一个简单示例,您可以根据需要进行修改:
public class FormatterModelBinder : DefaultModelBinder
{
internal static string TrimValue([CanBeNull] string value, [CanBeNull] FormatAttribute formatter)
{
if (string.IsNullOrEmpty(value)) return value;
return ((formatter == null) || formatter.Trim) ? value.Trim() : value;
}
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if ((propertyDescriptor != null) && (propertyDescriptor.PropertyType == typeof(string)))
{
var stringValue = value as string;
var formatter = propertyDescriptor.Attributes.OfType<FormatAttribute>().FirstOrDefault();
stringValue = TrimValue(stringValue, formatter);
value = stringValue;
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
然后您可以创建一个属性来根据需要装饰属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class FormatAttribute : Attribute
{
public FormatAttribute()
{
Trim = true;
}
public bool Trim { get; set; }
}
这是由 ViewModel 中的属性上的属性“激活”的
Public Person
{
string firstName;
[Format(Trim = true)]
string SocialSecurityNumber;
}
修改它以允许加密应该相当简单。
关于c# - 在 MVC 4 中操作模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446410/