MVC 3 - 这将如何工作?
我一年多前就发表了这篇文章,我认为更新它是有意义的,因为它已经获得了相当多的浏览量。
我要么错过了一些东西,要么微软真的把 MVC 搞砸了。我从事 Java MVC 项目,它们干净、简单。然而,在我看来,这完全是一团糟。 NerdDinner 等在线示例和 ASP.Net 上讨论的项目都太基础了,因此它们“简单”工作。如果这听起来很消极,请原谅,但这是我迄今为止的经验。
我有一个存储库和一个与存储库通信的服务。控制器呼叫服务人员。
我的数据层不是独立于持久性的,因为这些类是由 SQL Metal 生成的。因此我有很多不必要的功能。理想情况下我想要 POCO,但我还没有找到实现这一目标的好方法。
*更新:当然,微软并没有搞砸任何事情——我搞砸了。我并不完全理解我可以使用的工具。我所做的主要缺陷是我选择了错误的技术来持久化我的实体。 LINQ to SQL 在有状态应用程序中运行良好,因为可以轻松跟踪数据上下文。然而,在无状态上下文中情况并非如此。什么才是正确的选择?实体框架代码优先或仅代码工作得很好,但更重要的是,这并不重要。 MVC 或前端应用程序一定不应该知道数据是如何持久化的。 *
创建实体时,我可以使用对象绑定:
[HttpPost]
public ActionResult Create(Customer c)
{
// Persistance logic and return view
}
这效果很好,MVC 在幕后进行一些绑定,一切都“非常好”。
这不是“Jolly Good”。客户是一个领域模型,更糟糕的是,它依赖于持久介质,因为它是由 SQL Metal 生成的。我现在要做的是设计我的领域模型,该模型独立于数据存储或表示层。然后,我会从我的域模型创建视图模型并使用它。
一旦我想做一些更复杂的事情,例如 - 保存链接到客户的订单,一切似乎都会中断
[HttpPost]
public ActionResult Create(Order o)
{
// Persistance logic and return view
}
:订单我需要客户或至少客户 ID。 CustomerId 存在于视图中,但当它到达 Create 方法时,它已经丢失了 CustomerId。我不喜欢坐下来调试 MVC 代码,因为无论哪种方式我都无法在托管环境中更改它。
好吧,抱歉,这里有点抱怨。我现在要做的是创建一个名为 NewOrder、SaveOrder 或 EditOrder 的视图模型,具体取决于我想要实现的目标。该视图模型将包含我感兴趣的所有属性。顾名思义,开箱即用的自动绑定将绑定提交的值,并且不会丢失任何内容。如果我想要自定义行为,那么我可以实现自己的“绑定”,它将完成这项工作。
替代方法是使用 FormCollection:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
// Here I use the "magic" UpdateModel method which sometimes works and sometimes doesn't, at least for LINQ Entities.
}
这在书籍和教程中使用,但我没有看到任何意义。方法有一个替代方案:TryUpdateModel - 如果此崩溃或模型无效,它会尝试以任何一种方式更新它。您如何确定这会起作用?
与视图模型的自动绑定在大多数情况下都有效。如果没有,那么您可以覆盖它。你怎么知道它永远有效?你对它进行单元测试,你就睡得很好。
我尝试过的另一种方法是使用 ViewModel - 带有验证规则的包装对象。这听起来是个好主意,只是我不想向实体类添加注释。这种方法非常适合显示数据,但是在写入数据时该怎么办呢?
[HttpPost]
public ActionResult Create(CustomViewWrapper submittedObject)
{
// Here I'd have to manually iterate through fields in submittedObject, map it to my Entities, and then, eventually, submit it to the service/repository.
}
** 视图模型是一个很好的前进方向。必须有一些从视图模型到域模型的映射代码,然后可以将其传递给相关服务。这不是正确的方法,但它是这样做的一种方法。自动映射工具是您最好的朋友,您应该找到适合您要求的工具,否则您将编写大量样板代码。**
我是否遗漏了某些内容,或者这就是 Microsoft MVC3 应该工作的方式吗?我不明白这如何简化事情,特别是与 Java MVC 相比。
如果这听起来很负面,我很抱歉,但这是我迄今为止的经历。我很欣赏这个框架正在不断改进,引入了像 UpdateModel 这样的方法,但是文档在哪里?也许是时候停下来思考一下?我希望我的代码始终保持一致,但根据我迄今为止所看到的情况,我不相信这是正确的前进方向。
我喜欢这个框架。有太多东西需要学习,而且没有比以往任何时候都更令人兴奋的了。也许应该再发表一篇关于网络表单的文章。我希望这对您有所帮助。
I have made this post over a year ago, and I think it makes sense to update it as it's getting quite a few views.
I'm either missing something out or Microsoft has really messed up MVC. I worked on Java MVC projects and they were clean and simple. This is however a complete mess IMO. Examples online such as NerdDinner and projects discussed on ASP.Net are too basic, hence why they "simply" work. Excuse if this sounds negative, but this is my experience so far.
I have a repository and a service that speaks to the repository. Controllers call service.
My data layer is NOT persistence independent, as the classes were generated by SQL metal. Because of this I have a lot of unnecessary functionality. Ideally I'd like to have POCO, but I didn't find a good way to achieve this yet.
*Update: Of course Microsoft hasn't messed anything up - I did. I didn't fully understand the tools that were at my disposal. The major flaw in what I have done, was that I have chosen a wrong technology for persisting my entities. LINQ to SQL works well in stateful applications as the data context can be easily tracked. However, this is not a case in stateless context. What would be the right choice? Entity Framework code first or code only work pretty well, but what's more importantly, is that it shouldn't matter. MVC, or front end applications must should not aware of how data is persisted. *
When creating entites I can use object binding:
[HttpPost]
public ActionResult Create(Customer c)
{
// Persistance logic and return view
}
This works great, MVC does some binding behind the scene and everything is "jolly good".
It wasn't "Jolly Good". Customer was a domain model, and what was worse, it was dependent on persistence medium, because it was generated by SQL metal. What I would do now, is design my domain model, which would be independent of data storage or presentation layers. I would then create view model from my domain model and use that instead.
As soon as I'd like to do some more complex, e.g. - save Order which is linked to the customer everything seems to break:
[HttpPost]
public ActionResult Create(Order o)
{
// Persistance logic and return view
}
To persist an order I need Customer or at least CustomerId. CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId. I don't fancy sitting around debugging MVC code as I won't be able to change it in a hosting envrionment either way.
Ok, a bit of moaning here, sorry. What I would do now, is create a view model called NewOrder, or SaveOrder, or EditOrder depending on what I'm trying to achieve. This view model would contain all the properties that I'm interested in. Out-of-the-box auto binding, as the name implies, will bind submitted values and nothing will be lost. If I want custom behaviour, then I can implement my own "binding" and it will do the job.
Alternative is to use FormCollection:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
// Here I use the "magic" UpdateModel method which sometimes works and sometimes doesn't, at least for LINQ Entities.
}
This is used in books and tutorials, but I don't see a point in a method which has an alternative: TryUpdateModel - if this crashes or model is invalid, it attempts to update it either way. How can you be certain that this is going to work?
Autobinding with view models will work the most of the time. If it doesn't, then you can override it. How do you know it will always work? You unit test it and you sleep well.
Another approach that I have tried is using ViewModel - wrapper objects with validation rules. This sounds like a good idea, except that I don't want to add annotations to Entity classes. This approach is great for displaying the data, but what do you do when it comes to writing data?
[HttpPost]
public ActionResult Create(CustomViewWrapper submittedObject)
{
// Here I'd have to manually iterate through fields in submittedObject, map it to my Entities, and then, eventually, submit it to the service/repository.
}
** View model is a good way forward. There would have to be some mapping code from view model to the domain model, which can then be passed to the relevant service. This is not a correct way, but it's one way of doing it. Auto mapping tools are you best friends and you should find the one that suits your requirements, otherwise you'll be writing tons of boilerplate code.**
Am I missing something out or is this the way Microsoft MVC3 should work? I don't see how this is simplifying things, especiialy in comparisson to Java MVC.
I'm sorry if this sounds negative, but this has been my experience so far. I appreciate the fact that the framework is constantly being improved, methods like UpdateModel get introduced, but where is the documentation? Maybe it's time to stop and think for a little bit? I prefer my code to be consistent throughout, but with what I have seen so far, I have no confidence whatsoever that this is a right way forward.
I love the framework. There is so much to learn and it's not a lot more exciting then it has ever been. Should probably make another post regarding web forms. I hope this is helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
1) 对于保存订单且没有CustomerId的情况。如果
Order
上有一个 CustomerId 属性,并且您有一个强类型视图,那么您可以通过添加将其保留回您的控制器操作。这样做将使默认模型绑定器为您填充内容。
2)关于使用视图模型,我推荐这种方法。如果您使用 AutoMapper 之类的东西,您可以减轻冗余映射场景的一些痛苦。如果您使用类似 Fluent Validation 的东西,那么您可以很好地分离验证问题。
这里有一个很好的链接通用 ASP.NET MVC 实现方法。
1) For the case of saving an order, and not having CustomerId present. If
Order
has a CustomerId property on it, and you have a stongly typed view, then you can persist this back to your controller action by addingDoing this will have the default model binder populate things for you.
2) With respect to using a view model, I would recommend that approach. If you utilize something like AutoMapper you can take some of the pain out of redundant mapping scenarios. If you use something like Fluent Validation then you can separate validation concerns nicely.
Here's a good link on a general ASP.NET MVC implementation approach.
我认为您的问题不在于 asp.net MVC,而在于您选择一起使用的所有部分。
你想要原始而简单的吗?
到处使用 POCO,并在需要的地方实现存储库。
我没有使用过 Java MVC,但如果您在其中包含如何解决特定问题,那么整个问题看起来就不那么像咆哮了。
让我们澄清一些误解或可能的误解:
I don't think your issue is with asp.net MVC but with all the pieces You Choose to use together.
You want it raw and simple?
Use POCOs all around, and implement the repository where you need it.
I haven't used Java MVC, but it'd make the whole question look less like a rant if you include how you solved the particular problem in there.
Let's clear some misconceptions or maybe miscommunication:
如果您的视图定义正确,那么您可以轻松执行此操作>
编辑:
正如attadieni提到的,通过正确的观点,我的意思是你在表单标签中有类似的东西>
ASP.NET MVC 会自动绑定到相应的参数。
If your view is correctly defined then you can easily do this >
EDIT:
as attadieni mentioned, by correct view I meant you have something like this inside the form tag >
ASP.NET MVC will automatically bind to the respective parameters.
我一定是错过了这个问题。
正如您所说,您有一个带有 Create 操作的控制器 Order:
Create 操作回发一个 OrderCreateViewModel 类型的视图模型,如下所示。
您的视图有一个客户下拉列表,您可以将其作为属性添加到视图模型或文本框中,通过 JQuery 连接到该文本框以在服务器端进行搜索,在其中您可以在匹配时设置 CustomerId 的隐藏字段,但是你决定这样做。如果您已经提前知道 customerId(其他一些帖子似乎暗示了这一点),那么只需将其设置在视图模型中并绕过上述所有内容即可。
您拥有所有订单数据。您已将此订单附加到该客户的客户 ID。你可以走了。
什么?为什么?如果 CustomerId 位于视图、设置和回发中,那么它位于 HttpPost Create 方法的模型中,而这正是您需要它的位置。你说它丢失了是什么意思?
ViewModel 被映射到 order 类型的 Model 对象。正如建议的,使用 AutoMapper 很有帮助......
这不是必需的,您可以手动映射它,但它只是让事情变得更容易。
你就准备好了。如果您不想使用数据注释进行验证,那么可以在服务层中进行,使用提到的流畅验证库,无论您选择什么。使用所有数据调用服务层的 Create() 方法后,就可以开始了。
哪里断了?我们缺少什么?
ataddeini的答案是正确的,我只是想展示更多的代码。投票赞成
I must be missing the problem.
You have a controller Order with an Action of Create just like you said:
The Create action posts back a view model of type OrderCreateViewModel that looks like such.
Your view has a dropdown list of customers which you could add as a property to the viewmodel or a textbox which you wire up to to searching on the server side via JQuery where you could set a hidden field of CustomerId when a match is made, however you decide to do it. And if you already know the customerId ahead of time (which some of the other posts seems to imply) then just set it in the viewmodel and bypass all the above.
You have all of your order data. You have the customer Id of the customer attached to this order. You're good to go.
What? Why? If CustomerId was in the view, set, and posted back, it's in the model for the HttpPost Create method which is exactly where you need it. What do you mean it's being lost?
The ViewModel gets mapped to a Model object of type order. As suggested, using AutoMapper is helpful...
It's not a necessity, you can map it manually, but it just makes things easier.
And you're set. If you don't want to use data annotations for validation, fine, do it in the service layer, use the fluent validation library mentioned, whatever you choose. Once you call the Create() method of your service layer with all the data, you're good to go.
Where's the disconnect? What are we missing?
ataddeini's answer is correct, I'm just trying to show a bit more code. Upvote ataddeini
如果客户 ID 已存在于订单模型中(在本示例中),则无需扩展方法签名即可使用它。如果您在渲染视图上查看源代码,客户 ID 是否正确地在表单内的隐藏字段中发出?您是否在订单模型类上使用 [Bind] 属性并无意中阻止了客户 ID 的填充?
If the Customer Id is already in the Order model (in this example) it should be available without extending the method signature. If you view the source on the rendered view, is the customer id correctly emitted in a hidden field within the form? Are you using the [Bind] attribute on the Order model class and inadvertently preventing the Customer Id from being populated?
我认为 Order 表将包含一个 CustomerID 字段,如果是这样,唯一的问题是您可能没有在视图中包含任何控件来保留该值,然后就会丢失。
尝试遵循这个例子。
1) 发送到视图之前的 GET 操作,假设您此时分配了 CustomerID。
2)视图,如果您不使用任何控件来控制CustomerID,如文本框、组合框等,则必须使用隐藏字段来保留值。
3) 最后,POST 操作获取并保存订单。在这里,由于CustomerID被保留在隐藏值中,Model Binder会自动将所有Form值放入Order对象o中,然后您只需使用CRUD方法并将其持久化即可。
可以采用两种方法来实现此目的,一种是隐式保存所有模型值,即使未在视图中使用,另一种是仅保留那些使用的值。我认为 MVC 正在做正确的事情来遵循后来的做法,避免不必要地为更大的模型保留大量垃圾,而唯一的想法是,举个例子,一个 CustomerName,不知怎的,它可以让你控制在整个过程中保留哪些数据。整个循环动作-视图-动作并节省内存。
对于更复杂的场景,并非所有字段都在同一模型中,您需要使用 ViewModel。例如,对于细节场景,您将创建一个具有两个属性的 OrderViewModel:Order o 和 IEnumerable<<。订单详情>> od,但同样,您需要显式使用视图中的值,或使用隐藏字段。
在最近的版本中,您现在可以使用 POCO 类和 Code-First,这使得一切变得更干净、更容易,您可能想尝试 EF4 + CTP5。
I would think the Order table would include a CustomerID field, if so, the only problem is maybe you are not including any control in the view to keep that value, then is lost.
Try to follow this example.
1) GET action before sending to the View, let's say you assign the CustomerID at this point.
2) The View, if you don't use any control for the CustomerID, like textbox, combobox, etc, you must use a hidden field to keep the value.
3) Finally, the POST action to get and persist the order. In here, as CustomerID was kept in the hidden value, the Model Binder will automatically put all the Form values into the Order object o, then you just need to use CRUD methods and persist it.
Can be two approaches for this, one to implicit save all Model values even if not used in the View, and the other is to keep only those values used. I think MVC is doing the right thing to follow the later, avoid unnecessary keep a lot of junk for bigger models, when the only think is, to name one, a CustomerName, somehow it can give you control on what data to keep through the whole cycle action-view-action and save memory.
For more complex scenarios, where not all fields are in the same model, you need to use ViewModels. For example for mater-detail scenarios you would create a OrderViewModel that has two properties: Order o, and IEnumerable< OrderDetail > od, but again, you will need explicit use the values in the View, or use hidden fields.
In recent releases now you can use POCO classes and Code-First that makes all cleaner and easier, You may want to try EF4 + CTP5.
如果您正在使用服务(又名:服务层、业务门面)来处理 OrderModel,您可以提取一个接口,并让您的 ViewModel/DTO 来实现它,以便您可以将 ViewModel/DTO 传回给服务。
如果您使用存储库直接管理控制器中的数据(没有服务层),那么您可以使用从存储库加载对象然后对其执行 UpdateModel 的好旧方法来实现。
另外,URL 可能会在有意义的地方有所帮助,我的意思是您可以在 url 中添加客户标识符来创建订单。
UpdateModel 应该可以工作,如果您的 FormCollection 具有不可为 null 的属性值,并且它们在 FormCollection 中为空/null,则 UpdateModel 应该失败。
if you are using services (aka; service layer, business facade), to process lets say the OrderModel, you can extract an Interface, and get your ViewModel/DTO to implement it, so that you can pass back the ViewModel/DTO to the service.
If you are using Repositories to directly manage the data (without a servie layer) in the controller, then you can do it the good old way of Loading the object from a repository and then doing an UpdateModel on it.
Also, URLs might help a bit where it makes sense, I mean you can add the customer identifier in the url to create the order for.
UpdateModel should work, if your FormCollection has values for non-nullable properties and they are empty/null in the FormCollection, then UpdateModel should fail.