ASP.Net MVC你应该为每个视图创建一个模型? [英] ASP.Net MVC should you create a model for each view?

查看:131
本文介绍了ASP.Net MVC你应该为每个视图创建一个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的ASP.Net MVC和我发现自己做一个模型类为每个视图。例如。 SignInModel,SignUpModel,EditProfileModel等等。

许多这些有几分相似,具有相同的DB fiels,然后几个自定义属性。

这是真正的MVC应该是怎样做的,还是我错过了它的某些方面?

我意识到这可能是主观的,但应该有一个最佳实践解决这个问题。


解决方案

  

这是真正的MVC应该是怎样做的,还是我错过了它的某些方面?


这就是它绝对MVC如何应该做,你不会错过它的任何方面。

按次视图模型。

您还可以让你的视图模型的基本视图模型类和使用继承,但会特别有可能是不同的视图之间不同的验证规则小心。因此,例如,如果在一个视图中所需的属性,可能不再需要在另一个视图,所以如果你已经使用了基本视图模型类和数据注解你会是pretty多烤。

不要一秒钟犹豫,即使你重复一些属性创建视图模型。这就是视图模型都是为了=>为心目中的观点和熊的特殊需求,这些需求可能会经常发生变化,所以有独立的视图模型看起来开头难,但在长远来看,它是最好的解决办法无论是在维护和良好做法,恕我直言的条款。

I'm fairly new to ASP.Net MVC and I find myself making a single model class for every view. E.g. SignInModel, SignUpModel, EditProfileModel and so forth.

Many of these are somewhat similar, having the same DB fiels, and then a few custom properties.

Is this really how MVC is supposed to be done, or did I miss some aspect of it ?

I realize this may be subjective, but there ought to be a "best-practice" around this.

解决方案

Is this really how MVC is supposed to be done, or did I miss some aspect of it ?

That's absolutely how it MVC is supposed to be done and you aren't missing any aspect of it.

A View Model per View.

You could still have base view model classes and use inheritance of your view models but be careful especially with the validation rules which might be different between the different views. So for example if on one view a property was required it might no longer be required on another view so if you have used a base view model class and data annotations you would be pretty much toasted.

Do not for one second hesitate to create view models even if you repeat some properties. That's what view models are meant for => respond to the specific needs of a view and bear in mind that those needs could change quite often, so having separate view models might look difficult at the beginning but at the long term it is the best solution both in terms of maintenance and good practices IMHO.

这篇关于ASP.Net MVC你应该为每个视图创建一个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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