gpt4 book ai didi

c# - 如何让 ModelBinder 为参数返回 null?

转载 作者:太空狗 更新时间:2023-10-30 00:33:31 27 4
gpt4 key购买 nike

我有一个 POCO,我将其用作 MVC3 中操作的参数。像这样:

我的类型

public class SearchData
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}

我的行动

public ActionResult Index(SearchData query)
{
// I'd like to be able to do this
if (query == null)
{
// do something
}
}

目前,query作为 SearchData 的实例传递所有属性为 null .我宁愿得到一个 null对于 query所以我可以做上面代码中的空检查。

我总能看到 ModelBinder.Any()或者只是 ModelBinder 中的各种键查看它是否具有 query 的任何属性,但我不想使用反射来遍历 query 的属性.另外,我只能使用 ModelBinder.Any()检查查询是否是我唯一的参数。一旦我添加了额外的参数,该功能就会中断。

使用 MVC3 中当前的模型绑定(bind)功能,是否有可能获得为操作的 POCO 参数返回 null 的行为?

最佳答案

您需要实现自定义模型绑定(bind)器才能执行此操作。您可以只扩展 DefaultModelBinder

public override object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
object model = base.BindModel(controllerContext, bindingCOntext);
if (/* test for empty properties, or some other state */)
{
return null;
}

return model;
}

具体实现

这是绑定(bind)器的实际实现,如果所有属性都为 null,它将为模型返回 null。

/// <summary>
/// Model binder that will return null if all of the properties on a bound model come back as null
/// It inherits from DefaultModelBinder because it uses the default model binding functionality.
/// This implementation also needs to specifically have IModelBinder on it too, otherwise it wont get picked up as a Binder
/// </summary>
public class SearchDataModelBinder : DefaultModelBinder, IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// use the default model binding functionality to build a model, we'll look at each property below
object model = base.BindModel(controllerContext, bindingContext);

// loop through every property for the model in the metadata
foreach (ModelMetadata property in bindingContext.PropertyMetadata.Values)
{
// get the value of this property on the model
var value = bindingContext.ModelType.GetProperty(property.PropertyName).GetValue(model, null);

// if any property is not null, then we will want the model that the default model binder created
if (value != null)
return model;
}

// if we're here then there were either no properties or the properties were all null
return null;
}
}

将其添加为 global.asax 中的 Binder

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(SearchData), new SearchDataModelBinder());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

MvcHandler.DisableMvcResponseHeader = true;
}

关于c# - 如何让 ModelBinder 为参数返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11475684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com