ASP.NET MVC:将表单POST绑定到参数时避免紧密耦合 [英] ASP.NET MVC: avoid tight coupling when binding form POST to parameter

查看:74
本文介绍了ASP.NET MVC:将表单POST绑定到参数时避免紧密耦合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个类似的界面:

Let's say I have an interface like:

interface IThing {
   int Id { get; set; }
   string Title { get; set; }
}

在ASP.NET MVC中,我有一个表单可以发布到这样的控制器操作中:

And in ASP.NET MVC I have a form that posts to a controller action like this:

 [AcceptVerbs(HttpVerbs.Post)]
 public ActionResult NewThing([Bind(Exclude = "Id")] SimpleThing thing) {

    // code to validate and persist the thing can go here            
 }

其中 SimpleThing 是一个具体的类,仅勉强实现了 IThing .

Where SimpleThing is a concrete class that just barely implements IThing.

但是,我希望我所有的方法都可以处理该接口.我有一个使用NHiberate及其自己的 IThing 实现的数据程序集(我们称其为 RealThing ).我无法将SimpleThing传递给它,因为它会抱怨未知实体".

However, I would like all my methods to deal with the interface. I have a data assembly that uses NHiberate and its own IThing implementation (let's call it RealThing). I can't pass the SimpleThing to it because it will complain about an "unknown entity".

有人对采用更清洁的方法有任何想法吗?我在考虑使用工厂类的思路.但是我该如何使用MVC表单活页夹来使用它呢?

Does anyone have any ideas about a cleaner way to do this? I was thinking about something along the lines of using a factory class. But how would I get the MVC form binder to use it?

谢谢!

推荐答案

这里有一些很好的建议,实际上我提出了一个可行的解决方案.但是,我最终得到了一些东西.我刚刚创建了特定于我要发布的表单数据的模型,并使用了默认的模型绑定器.

There were some good suggestions here and I actually came up with a solution that works. However, I ended up with something altogether. I just created models specific for the form data I was posting and used the default model binder.

简单得多,它使我可以捕获不属于域模型的数据(例如,像评论"字段).

Much simpler and it allows me to capture data that isn't part of my domain model (ie. like a "comments" field).

这篇关于ASP.NET MVC:将表单POST绑定到参数时避免紧密耦合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆