它是在MVC使用控制器模型类一个不好的做法? [英] Is it a bad practice using model classes in controller in mvc?

查看:157
本文介绍了它是在MVC使用控制器模型类一个不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与最佳实践进行比较,在asp.net mvc的一个ORM或数据库表时。其中一个我有重大问题是我应该的实例化模型类直接在controller..not查询数据库中,但只使用模型类来存储值。

I wanted to compare with best practices when working with an ORM or database tables in asp.net mvc. One of the major questions I have is should I instantiate the model classes directly in controller..not query the database but just use the model class to store the values.

有关如如果我使用实体框架模型...那么它是一个不好的做法,使用该实体类对象的控制器。有些时候,它只是更容易直接使用的控制器,而不是创建的ViewModels甚至ViewData的生成的数据库类。我们有一个数据访问层,其中应用了所有的查询和业务逻辑,业务层,但更容易,虽然我不喜欢访问控制器模型的想法,但它是一个真正的坏习惯

For e.g. If I am using entity framework as model...then is it a bad practice to use the entity class objects in the controller. There are times when it is just easier to directly use the database classes generated in the controller instead of creating ViewModels or even ViewData. We have a data access layer and a Business layer where all the querying and business logic is applied but although easier I don't like the idea of accessing the model in the controller but is it really a bad practice?

推荐答案

是的,这是因为问题的一个不好的做法,过过账。

Yes, it is a bad practice, because of the problem of "over-posting".

例如,考虑一个实体模型为用户配置:

For instance, consider an Entity model for a UserProfile:

  public class UserProfile
  {
    public string UserName { get; set; }
    public bool IsAdmin { get; set; }
    public string EmailAddress { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
  }

您的用户个人资料页面,用户可以编辑自己的名字,姓氏,和EmailAddress的。

Your user profile page allows the user to Edit their FirstName, LastName, and EmailAddress.

这是不道德的用​​户可以简单地修改表单张贴IsAdmin与其他值一起。因为你的动作期望用户配置的输入,IsAdmin值将被映射为好,并最终坚持着。

An unscrupulous user could simply modify the form to post "IsAdmin" along with the other values. Because your Action is expecting an input of UserProfile, the IsAdmin value will be mapped as well, and eventually persisted.

下面是<一个href=\"http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html\"相对=nofollow>有关之下,overposting 的危险极好的书面记录。

Here is an excellent writeup about the perils of under and overposting.

我认为没有错直接结合实体模型,您的[HTTPGET]的方法,虽然。

I see nothing wrong with binding Entity models directly to your [HttpGet] methods, though.

这篇关于它是在MVC使用控制器模型类一个不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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