MVC - 作为控制器操作参数的接口

发布于 2024-10-31 23:09:30 字数 816 浏览 1 评论 0原文

我想将实现接口的多个类之一从我的视图传递回我的控制器操作。我在视图中使用 ActionLink 将实例传递给我的操作,但它自然会失败,因为 MVC 无法通过默认模型绑定处理接口。

所以 :

<%=Html.ActionLink(flow.Source.Name, "Get", new {container=flow.Source})%>

是在一个循环中,并且每个 flow.Source 都符合 IContainer。

public class Flow 
{
    public virtual IContainer Source { get; private set; }
}

public interface IContainer
{
//members here
}

public class File : IContainer
{}

public class Worksheet : IContainer
{}

基本上我想调用一个操作方法:

public ActionResult Get(IContainer container)
{
   // Do something
}

原因是我需要检索从数据库传递给我的操作方法的当前容器的状态。我使用 NHibernate 并将实体映射到每个实体的表上,例如,一个用于文件,一个用于工作表,因此需要能够决定使用哪个数据访问类。有道理吗?可能不是!

这可以在不转向基类容器的情况下完成吗?我可以坚持将接口传递给我的操作方法并解析代替该接口传递的子类型实例吗?

如有任何帮助,我们将不胜感激。

I want to pass one of a number of classes that implement an interface from my view back to my controller action. I use an ActionLink in my view passing the instance to my action, but it naturally fails because MVC cannot deal with interfaces via default model binding.

So :

<%=Html.ActionLink(flow.Source.Name, "Get", new {container=flow.Source})%>

is in a loop and each flow.Source conforms to IContainer.

public class Flow 
{
    public virtual IContainer Source { get; private set; }
}

public interface IContainer
{
//members here
}

public class File : IContainer
{}

public class Worksheet : IContainer
{}

Basically I want to call an action method :

public ActionResult Get(IContainer container)
{
   // Do something
}

The reason being that I need to retrieve the state of the current container passed to my action method from the database. I use NHibernate and have entities mapped on a table per entity, so have one for File and one for Worksheet for example, so need to able to decide which data access class to use. Make sense? Probably not!

Can this be done without moving towards a base class Container? Can I stick with an interface being passed to my action method and resolve the subtype instance passed in place of the interface?

Any help with this would be gratefully appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜雨飘雪 2024-11-07 23:09:30

当您调用类时,接口需要“一些”具体实现来引用。我认为从你的帖子来看你已经意识到了这一点:)
话虽如此,这里处理的方法是“有点”,您只需创建自己的模型绑定器,它必须知道(或如何)映射到并创建具体类型(直接或通过依赖项注入)

ASP.NET MVC - 接口类型上的自定义模型绑定器

An interface needs 'some' concrete implementation to reference when you would call your class. I think judging by your post you are aware of this : )
With that said there is 'kinda' of an approach handled here where you just create your own model binder that has to know about (or how) to map to and create a concrete type (either directly or by dependency injection)

ASP.NET MVC - Custom Model Binder on Interface Type

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文