是否有意义有在的WebAPI的ViewModels? [英] Does it Make Sense to have ViewModels in the Webapi?

查看:406
本文介绍了是否有意义有在的WebAPI的ViewModels?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习的WebAPI和发现自己做的东西是有道理的在MVC项目,但可能没有意义。

通常在一个MVC项目,我做的ViewModels和使用,作为参数,或者他们的观点回传。

由于在没有的WebAPI的意见我想这没有意义有一个视图模型作为参数。<​​/ P>

我不知道,也许我是否应该只是作为一个参数我EF域(code第一),并把数据注解对这些顶级。我通常会把标注在视图模型属性,我喜欢这种过度的域。

但什么是从这样阻止我就是我不是100%清楚我的MVC网站将如何工作。

是否MVC网站只是回吐simples的意见,然后你使用jQuery打电话给你的WebAPI或者你只是调用MVC操作方法直接只需调用同一方法的WebAPI会叫?

如果是第二种方式,然后我宁愿把我的视图模型中的数据再次说明,但随后我把在EF域和虚拟机,并​​且看起来是多余的都是相同的。


解决方案

术语不谈,具有结合车型使用的依然。他们只是在技术上并非不再的ViewModels,因为你说得有没有参与意见。但它们的使用肯定还是。使用它们可采取在模型的属性属性的优势,可以让你在需要重用它们在你的API。还要记住,如果你使用的实体直接的WebAPI将模型中的所有参数绑定到他们比赛的名字,即使你不是故意的。

此外,实体模型被重新$原始数据的对$ psentations,但用于针对绑定模型是该API请求需要满足成功处理请求的固定合同。该值可能最终被您的实现完成时间跨越多个实体模型,没有不被持久化到数据存储的。

I am starting to learn the webapi and find myself doing stuff that makes sense in an MVC project but may not make sense in.

Normally in an MVC project I make ViewModels and use that as the parameter or pass them back with the view.

Since there are no views in webapi I guess it does not make sense to have a ViewModel as parameter.

I am wondering maybe if I should just have as a Parameter my EF domains(code first) and put data annotations on top of these. I normally would put the annotations over the view model properties as I liked this over the domain.

However what is stopping me from doing this is I am not 100% clear how my MVC site would work.

Does the MVC site just spit back simples views and then you use Jquery to call your webapi or do you just call MVC action methods that directly just call the same methods the Webapi would call?

If is the second way then I rather put the data annotations on my view model again but then I am putting the same ones on both the EF domain and VM's and that seem redundant.

解决方案

Terminology aside, having models for binding to is still of use. They just aren't technically ViewModels anymore, in that you're right there are no views involved. But they are definitely still of use. Using them allows you to take advantage of attributes on your Model's properties and allows you to reuse them across your API if needed. Also remember if you use your entities directly WebAPI will model bind all parameters to them that match by name, even if you didn't mean to.

Also, the Entity Models are representations of your raw data, but the Models used for binding against are a fixed contract that the API requests need to satisfy to successfully process a request. The values in which could end up spanning multiple entity models by the time your implementation is done, not not be persisted to a data store at all.

这篇关于是否有意义有在的WebAPI的ViewModels?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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