我有一个这样的模型绑定器:
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等,而不影响其他值。谢谢
1条答案
按热度按时间yfwxisqw1#
当模型对象被发布时,空的字符串值被转换为null。这是MVC模型绑定器的默认行为。您可以尝试这样的解决方案,
公共密封类EmptyStringModelBinder:默认模型绑定器{公共覆盖对象绑定模型(控制器上下文控制器上下文,模型绑定上下文绑定上下文){绑定上下文.模型元数据.将空字符串转换为空= false;//绑定器=新的模型绑定器字典(){默认绑定器=此};返回base.BindModel(控制器上下文,绑定上下文);}}