c# - 在 MVC 4 中操作模型绑定(bind)

标签 c# asp.net-mvc-4 model-binding

用一个例子更容易解释。假设我有一个人类

Public Person
{
string firstName;
string SocialSecurityNumber;
}

当用户在网页中进行某些更改时,Person 对象将被发送回接受 Person 作为输入参数的 Controller 。社会安全号码已加密。我们有许多页面回发对象(不一定是 Person 类),这些对象已加密的社会保障作为参数。现在我想修改模型绑定(bind),以便如果发布的对象具有 SocialSecurityNumber 作为属性,则应该自动解密。我怎样才能做到这一点?

最佳答案

您可以使用自定义模型绑定(bind)器。一些例子:

这是我之前使用过的一个简单示例,您可以根据需要进行修改:

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/

相关文章:

c# - 如何指示 TypeConverter 中的错误

c# - 字符串中只允许单一类型的标记

c# - MVC5 和 SSRS ReportViewer - 如何实现?

c# - 防止外部代码修改C#中的私有(private)数据

asp.net-mvc-4 - Visual Studio 2010无法访问webapi项目

c# - 列表的 MVC 模型绑定(bind)动态列表

c# - 参数化查询构建错误

c# - 如何仅在应用程序打开并运行时在后台运行方法?

asp.net-mvc-4 - 升级到 .NET 4.5 和 EF 5 后“启用迁移”失败

c# - 对方法参数的 BindAttribute 进行单元测试