gpt4 book ai didi

asp.net-mvc-3 - 仅适用于 MVC 应用程序的一个领域的自定义模型绑定(bind)器

转载 作者:行者123 更新时间:2023-12-04 18:14:23 25 4
gpt4 key购买 nike

我使用了在 Global.asax 文件中配置的自定义模型绑定(bind)器。是否可以仅在应用程序的某些区域下使用此模型绑定(bind)器?

public class CreatorModelBinder : IModelBinder
{

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//what logic can i put here so that this only happens when the controller is in certain area- and when it's not in that area- then the default model binding would work
var service = new MyService();
if (System.Web.HttpContext.Current != null && service.IsLoggedIn)
return service.Creator;
return new Creator {};
}
}

最佳答案

如果你想调用默认模型绑定(bind)器,你应该从 DefaultModelBinder 派生。而不是直接实现 IModelBinder界面。

接着:

public class CreatorModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var area = controllerContext.RouteData.Values["area"] as string;
if (string.Equals(area, "Admin"))
{
// we are in the Admin area => do custom stuff
return someCustomObject;
}

// we are not in the Admin area => invoke the default model binder
return base.BindModel(controllerContext, bindingContext);
}
}

关于asp.net-mvc-3 - 仅适用于 MVC 应用程序的一个领域的自定义模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11990814/

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