2

如何修改 ModelBinder 以使用 FlagsEnum (Enum: byte)?我将显示代码:

代码

枚举

[Flags]
public enum TipoPessoaEnum : byte
{
    Comprador = 1
    ,
    Proprietario = 2
    ,
    GerenteAgencia = 4
}

班级

public class PessoaViewModel
{
    public string Nome { get; set; }
    public DateTime? DataNascimento { get; set; }
    public TipoPessoaEnum? Tipo { get; set; }
    // Other fields have been omitted
}

json

{"Id":0,"Nome":"Teste Flags 02","Tipo":["Comprador","Proprietario"],"Genero":"Masculino","Escolaridade":"","EstadoCivil":"","RegimeCasamento":"","Telefones":[],"Emails":[],"Enderecos":[]}

模型粘合剂

不使用 JSON时工作,两个 Enuns 作为 FlagsEnuns。

public class CreditoImobiliarioModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null) throw new ArgumentNullException("bindingContext");

        if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
        {
            var values = GetValue<string[]>(bindingContext, bindingContext.ModelName);
            var modelType = bindingContext.ModelType.GetNonNullableModelType();

            if (values != null && values.Length > 1 && (modelType.IsEnum && modelType.IsDefined(typeof(FlagsAttribute), false)))
            {
                long byteValue = 0;
                foreach (var value in values.Where(v => Enum.IsDefined(modelType, v)))
                    byteValue |= (byte)Enum.Parse(modelType, value);

                return Enum.Parse(modelType, byteValue.ToString());
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }

    private static T GetValue<T>(ModelBindingContext bindingContext, string key)
    {
        if (bindingContext.ValueProvider.ContainsPrefix(key))
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key);
            if (valueResult != null)
            {
                bindingContext.ModelState.SetModelValue(key, valueResult);
                return (T)valueResult.ConvertTo(typeof(T));
            }
        }
        return default(T);
    }
}

问题

可以看到,在 classPessoaViewModel中,属性Tipo可以为TipoPessoaEnum.

因为该属性Tipo可以取多个值,所以我发送(以 JSON 格式)一个Tipo "Tipo":["Comprador","Proprietario"]. 哪些是enuns的值。

如何将我的 json 数组映射 "Tipo":["Comprador","Proprietario"]到我的属性Tipo

模型粘合剂

GetValue<T>在类的方法中,CreditoImobiliarioModelBinderbindingContext.ValueProvider.GetValue("Tipo"); 返回 null ??

4

0 回答 0