简体   繁体   中英

When should I query from a database in my view, ASP.NET MVC

Problem:

If I have a scenario where I don't want to change my model properties and need to get one more attribute from some table, is it fine if I write a query inside a view and show the result?

If the answer is no, I would like to know why it's not considered a good way.

In my opinion you should never do that. Just because you loose the entire paradigm of the tool you are using.

In a few years, this is confusing to you, or someone else maintaining the code. If you don't want to change it all, use dynamic properties, ViewBag or other options to keep your flexibility, test-ability, etc.

Yes.

View is not a mirror of your data structure. Actually, often it's an aggregation and/or manipulation for user-friendly presentation of the data that stands behind.

First of all, the reason why it's called MVC is because of the separation of concerns. View's are only concerned of the User-Interface. Queries are done on the controller. Another is it would be too confusing if you would place everything in a single page which already defeats the purpose of having MVC.

Though there are cases when querying the database from a View may seem easier and appropriate, you should be ready for the consequences of breaking separation of concerns (SoC). When you spread your DAL across many layers it's going to be hard to re-factor the database in the future. Another question is security - if you decide to implement database security or controller-based security later, your view-based queries will be a security point.

However, if the project is small, I would trade SoC for performance.

In my opinion, you should never do queries in your Views . It's called MVC and the proper way of using it is to separate concepts.

You should have a Model , a Controller , a View and a Repository (as the simpliest approach). As the name suggests, View must be used only for displaying processed data.

More information about MVC best practices is here .

I remember when I started working with MVC. I didn't know about this and my teamleader told me it's never a good choice to do this.

Conclusion:

It's just a matter of design and perspective. If you're doing a project for yourself or for the university, organize your code as you wish. If you're working in a professional environment you should respect some working principles

Another important factor to think of, is this: if another person must refactor or modify your code he must know where to find methods, where to find models and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM