【问题标题】:ModelBinder converting existing values in properties to nullModelBinder 将属性中的现有值转换为 null
【发布时间】:2023-02-13 20:41:03
【问题描述】:

我有一个像这样的模型绑定器:

public class CustomQuarantineModelBinder : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (context.Metadata.ModelType.GetInterfaces().Contains(typeof(IQuarantineControl))
        {
            return new QuarantineModelBinder();
        }

        return null;
    }
}

public class QuarantineModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext modelBindingContext)
    {
        char[] delimeter = { '|' };

        if (modelBindingContext == null)
        {
            throw new ArgumentNullException(nameof(modelBindingContext));
        }

        var model = Activator.CreateInstance(modelBindingContext.ModelType);

        if (modelBindingContext.ModelType.GetInterfaces().Contains(typeof(IQuarantineControl)))
        {
            var qc = model as IQuarantineControl;

            if (qc != null)
            {
                var request = modelBindingContext.HttpContext.Request;
                string QuarantineControl = request.Form["QuarantineControl"];

                if (!string.IsNullOrEmpty(QuarantineControl))
                {
                    string[] components = QuarantineControl.Split(delimeter);

                    qc.QuarantineClear();
                    qc.QuarantineControlID = Convert.ToInt32(components[0]);
                    qc.QuarantineState = (QuarantineState)Convert.ToInt32(components[1]);
                    for (int i = 2; i < components.Length; i++)
                    {
                        qc.QuarantineReasons.Add(components[i]);
                    }
                }
            }
        }

        modelBindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;
    }

但是,模型中的其他字段变为 null 或空。我想在不影响其他值的情况下设置 QuarantineState、QuarantineControlId 等。谢谢

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-core


    【解决方案1】:

    发布模型对象时,空字符串值将转换为 null。这是 MVC 模型绑定器的默认行为。 您可以尝试这样的解决方法,

    公共密封类 EmptyStringModelBinder : DefaultModelBinder { 公共覆盖对象 BindModel(ControllerContext controllerContext, ModelBindingContext 绑定上下文) { bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; //Binders = new ModelBinderDictionary() { DefaultBinder = this }; 返回 base.BindModel(controllerContext, bindingContext); } }

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2012-02-18
      相关资源
      最近更新 更多