使模型绑定适用于没有默认构造函数的模型

2024-05-07

我一直在试图找到一种方法,让模型绑定与带有参数的构造函数的模型一起进行。

那个行动:

 [HttpPost]
        public ActionResult Create(Company company, HttpPostedFileBase logo)
        {
            company.LogoFileName = SaveCompanyLogoImage(logo);
            var newCompany = _companyProvider.Create(company);
            return View("Index",newCompany);
        }

和模型

public  Company(CustomProfile customProfile)
        {
            DateCreated = DateTime.Now;
            CustomProfile = customProfile;
        }

我已经完成了研究,似乎我需要搞乱我的 ninjectControllerfactory:

  public class NinjectControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel ninjectKernel;

        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }

        protected override IController GetControllerInstance(RequestContext requestContext,
                                                             Type controllerType)
        {
            return controllerType == null
                       ? null
                       : (IController) ninjectKernel.Get(controllerType);
        }

        private void AddBindings()
        {
            ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
            ninjectKernel.Bind<IMembershipProvider>().To<MembershipProvider>();
            ninjectKernel.Bind<ICustomProfileProvider>().To<CustomProfileProvider>();
            ninjectKernel.Bind<ICompanyProvider>().To<CompanyProvider>();
        }
    }

我还觉得我需要修改我的模型绑定器,但我不清楚前进的方向:

 public class CustomProfileModelBinder : IModelBinder
{
    private const string sessionKey = "CustomProfile";

    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
    {
        // get the Cart from the session 
        var customProfile = (CustomProfile) controllerContext.HttpContext.Session[sessionKey];
        // create the Cart if there wasn't one in the session data
        if (customProfile == null)
        {
            customProfile = new CustomProfile("default name");
            controllerContext.HttpContext.Session[sessionKey] = customProfile;
        }
        // return the cart
        return customProfile;
    }

    #endregion
}

希望这能解释我的问题,如果这是一个相当冗长的问题,我很抱歉!

感谢您的帮助


在这种情况下,您需要创建的参数(CustomProfile)似乎必须从会话中获取。然后,您可以为从默认模型绑定程序派生的 Company 模型使用特定的模型绑定程序,仅更改它创建 Company 类实例的方式(然后它将以与默认方式相同的方式填充属性):

public class CompanyModelBinder: DefaultModelBinder
{
    private const string sessionKey = "CustomProfile";

    protected override object CreateModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext,
                                         Type modelType)
    {
        if(modelType == typeOf(Company))
        {
            var customProfile = (CustomProfile) controllerContext.HttpContext.Session[sessionKey];
            // create the Cart if there wasn't one in the session data
            if (customProfile == null)
            {
                customProfile = new CustomProfile("default name");
                controllerContext.HttpContext.Session[sessionKey] = customProfile;
            }

            return new Company(customProfile);
        }
        else
        {
            //just in case this gets registered for any other type
            return base.CreateModel(controllerContext, bindingContext, modelType)
        }
    }
}

您只需将其添加到 global.asax Application_Start 方法中即可仅为 Company 类型注册此绑定程序:

ModelBinders.Binders.Add(typeOf(Company), CompanyModelBinder);

另一种选择可能是通过继承 DefaultModelBinder 使用 Ninject 依赖项创建依赖项感知模型绑定器(当您使用 Ninject 时,它知道如何构建具体类型的实例,而无需注册它们)。 但是,您需要配置一个自定义方法来在 Ninject 中构建 CustomProfile,我相信您可以使用 ToMethod() 来完成。 为此,您需要在控制器工厂之外提取 Ninject 内核的配置:

public static class NinjectBootStrapper{
    public static IKernel GetKernel()
    {
        IKernel  ninjectKernel = new StandardKernel();
        AddBindings(ninjectKernel);
    }

    private void AddBindings(IKernel ninjectKernel)
    {
        ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
        ninjectKernel.Bind<IMembershipProvider>().To<MembershipProvider>();
        ninjectKernel.Bind<ICustomProfileProvider>().To<CustomProfileProvider>();
        ninjectKernel.Bind<ICompanyProvider>().To<CompanyProvider>();
        ninjectKernel.Bind<CustomProfile>().ToMethod(context => /*try to get here the current session and the custom profile, or build a new instance */ );
    }
}

public class NinjectControllerFactory : DefaultControllerFactory
{
    private readonly IKernel ninjectKernel;

    public NinjectControllerFactory(IKernel kernel)
    {
        ninjectKernel = kernel;
    }

    protected override IController GetControllerInstance(RequestContext requestContext,
                                                         Type controllerType)
    {
        return controllerType == null
                   ? null
                   : (IController) ninjectKernel.Get(controllerType);
    }
}

在这种情况下,您将创建此模型绑定器:

public class NinjectModelBinder: DefaultModelBinder
{
    private readonly IKernel ninjectKernel;

    public NinjectModelBinder(IKernel kernel)
    {
        ninjectKernel = kernel;
    }

    protected override object CreateModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext,
                                         Type modelType)
    {
        return ninjectKernel.Get(modelType) ?? base.CreateModel(controllerContext, bindingContext, modelType)
    }
}

您可以将 global.asax 更新为:

IKernel kernel = NinjectBootStrapper.GetKernel();
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
ModelBinders.Binders.DefaultBinder = new NinjectModelBinder(kernel);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使模型绑定适用于没有默认构造函数的模型 的相关文章

随机推荐

  • 在 Bootstrap 导航栏后添加一些空间的最佳方法是什么?

    以下代码始终在页面顶部显示导航栏 我需要将第二个容器 内容 放置在导航栏的末尾而不是其下方 目前第二个容器位于导航栏下方 我可以在内容顶部添加一些空白 但我不确定这是一个好方法 知道如何解决吗 div class container div
  • 将 CSS 类应用于 asp:Hyperlink 中的图像?

    我使用 asp Hyperlink 根据 URL 中的参数动态呈现链接图像 我需要能够将 CSS 类添加到渲染的 img 中 但不知道如何做到这一点 我知道我可以将 CssClass blah 添加到asp Hyperlink 但在渲染的H
  • CSS3 过渡卡住了

    我们的新网站上正在进行很多转换 有一个特别之前工作得很好 但自从添加谷歌地图后 某种过渡效果不会触发 此外 它还会禁用网站上的所有其他过渡效果 直到触发另一个 javascript 函数 我不知道为什么 但这些就是事实 该问题似乎仅限于 S
  • 我的 QSqlQueryModel 不在列表视图中显示数据

    我正在玩 QSqlQueryModel 但我现在完全陷入困境 我一整天都在寻找解决方案 但到目前为止还没有运气 我所做的工作是它从我的 sqlite 数据库中提取数据 但由于某种原因我无法在列表视图中显示它 我的角色名似乎不存在 对于我从数
  • Typescript 1.8 模块:从文件夹导入所有文件

    我正在使用 Typescript 构建一个大型库 其中包含 100 个独立的 ts 文件 以前我用过导出模块XXX 重命名为导出命名空间 XXX稍后 对于我的所有课程 但正如书籍所说 这不是推荐的方法 我应该使用 import 代替 所以我
  • ActiveSupport 如何计算月度总和?

    我很高兴也很惊讶地发现 ActiveSupport 按照我想要的方式进行月度汇总 无论相关月份中有多少天 添加1 month对特定的Time将使您在该月的同一天着陆Time gt Time utc 2012 2 1 gt Wed Feb 0
  • Solr 您的意思是(拼写检查组件)

    我在我的应用程序中使用 solr 并集成了拼写检查组件 但我遇到了一些问题 第一的 当我输入一个用空格分隔的术语时 他们会给我每个术语的更正 Eg 水 gt 什么术语 但事实是watters 第二 当我输入一些带有错误术语的短语时 尽管其他
  • 向 Windows 服务发送 Windows 消息

    有没有任何工具可以将 WM ENDSESSION 等 Windows 消息发送 模仿 到 Windows 服务 OR 如何使用 C 向进程发送 Windows 消息 我只懂C 编辑 目的 基本上我必须调试 Windows 服务来修复仅在系统
  • 在Java中,如何在每次进入或退出给定对象的监视器时记录一条消息?

    我正在尝试调试一些使用一些自定义引用计数 锁定的 C Java 绑定 我想让 JVM 在每次给定对象进入或退出其监视器时打印一条消息 有什么办法可以做到这一点吗 基本上 我想要这个 synchronized lock System out
  • 使用 FormData 发送 XMLHttpRequest

    我正在尝试使用 JavaScript 制作 XHR 但无法使其正常工作 当我在 Chrome 开发者工具的 网络 选项卡中看到正确的请求时 我看到他们有一个 表单数据 部分其中列出了随请求发送的所有信息 如下所示 现在 我尝试让我的XMLH
  • 什么时候选择Spring框架?

    HI 我想知道什么时候我们必须选择Spring框架 选择spring框架有什么明显的优势吗 我不想知道其中的差异 而是选择其他技术 如 J2EE 等 为什么我们特别选择 Spring 问题是您是在谈论核心 Spring 框架 还是 Spri
  • 使用 PHP DOM 获取子节点的值

    下面是我使用的 XML 示例
  • -bash: gulp: 在 Mac 中找不到命令

    我尝试在 mac 中安装 gulp 如下所示 Is iMac itop npm root Users itop node modules Is iMac itop npm config set prefix usr local Is iMa
  • 如何在 WooCommerce 中添加属性术语图像?

    在 WooCommerce 中 我创建了一个属性 品牌 并添加了一些术语 例如 品牌一 品牌二 等 我想为每个术语添加图像 目前没有在属性项中添加图像的选项 请告诉我如何在属性项中添加图像 管理链接是这样的 wp admin edit ta
  • 查找手动注册(混淆)的本机函数地址

    我试图理解一个 Android 应用程序 其中包含一个名为foo在班上com app Bar 课堂内Bar有一个加载共享对象的静态子句System loadLibrary libfoo so 我认为是用它构建的 f可见性 隐藏 https
  • Matplotlib导入错误ft2font

    我在 64 位 Mac 上的 Canopy 下安装了 Python 2 7 6 Ipython 版本为 2 1 0 这是一个非常奇怪的问题 我不确定这是否是路径文件问题 每当我导入 matplotlib pyplot 不仅仅是 matplo
  • VBA 下标超出工作簿名称范围

    我从网上拉了一些代码来打开文件夹中的最新文件 这似乎工作得很好 然而 在代码的后面 我添加了一行附加行来设置最近打开的同一文件 尝试此操作时 工作簿 subscipt 超出范围 我认为这与语法有关 可能需要在工作簿名称中添加额外的引号 有什
  • JS:如何将此字符串转换为日期对象

    该字符串是 2012 04 13T22 59 33 我努力了Date parse str Y m dTH i s 这对我不起作用 我不确定 T 代表什么 只需将其作为日期的参数即可 var date new Date 2012 04 13T
  • kubernetes/openshift 中的请求与限制 cpu

    我在为 Openshift 中的 pod 选择正确的请求和限制设置时遇到一些困境 一些数据 在启动期间 应用程序需要至少 600 毫核才能在 150 秒内完成就绪检查 启动后 200 毫核应该足以让应用程序保持空闲状态 所以我从文档中的理解
  • 使模型绑定适用于没有默认构造函数的模型

    我一直在试图找到一种方法 让模型绑定与带有参数的构造函数的模型一起进行 那个行动 HttpPost public ActionResult Create Company company HttpPostedFileBase logo com