What is the purpose of the Model in MVC? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have read a lot about MVC, and I have even written a modestly sophisticated data-driven MVC mobile web app in .Net, but (since I am still learning), I did not see what to put in the model. The app had a dozen or so views, a primary controller, and helper files for SQL interactions and custom data types. I was able to data bind just fine without using the model, and custom data types worked as anticipated. Please be kind, what am I missing? What is the purpose of the model, and why should I be compelled use it (other than it being a standard)?

MVC is primarily a User Interface design pattern. The Model is a container for "everything else," everything that doesn't have to do with UI.
In general, you push as much logic as you can back from the View into the Controller or a ViewModel, and you make your controllers as thin as possible by pushing as much logic as you can back into the Model. So the short answer to "what goes in the Model" is "everything that doesn't go into a View, ViewModel or Controller."
Specifically:
Domain objects, like customer
Services
Business Logic
Server-side validation
Object-Relational mappers
Database
Repositories

Simply put - "The MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic.
With MVC, models both hold and manipulate application data."
You are not following the standard MVC pattern if you ignore the Model all together. However, as you found out - you don't need to use it. You can call into the database directly from the controllers and return types you've defined in the DAL (Data Access Layer) - which indirectly you are using as the Model in your design. This isn't good practice.
You should be compelled to follow the pattern so you achieve 'Separation of Concerns' in your application's architecture. You can find a lot of information online about this topic as it relates to the MVC pattern.
Model Definition

The View is a template that can be filled by passing a model containing data into it.
It allows the view to be customized depending on what the model contains.
How else are you filling data into your view?
Maybe jQuery gets?

In your case, the "helper files for SQL interactions and custom data types" is your model. The model is an abstraction over the true data source, eg the database.
For small projects, what you have done works just fine. As projects get larger though, binding the view directly to the database/model and not fully abstracting the model causes more and more problems.

Related

Business Logic on ASPNet MVC outside of Model [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been working with asp.net core web api for the past few days, I am familiar with MVC and SOC etc but I got confused a bit with the core mvc tutorials.
So in all the tutorials (to keep them simple) they put the business logic inside the Controller, but this is ofcourse not compliant to MVC.
In general I have created:
Model (to create the DB structure through EF)
Controller (to serve the endpoints and act)
Repositories (to provide the query logic to the DB)
Now I am bit confused with Services and also where am I supposed to put the business logic? I mean the Model is one place, but I dont want my controller to access the model directly but more like a Facade/Factory.
How do we achieve this in aspnet?
You can find my working repo at https://github.com/drakoumel/DatacircleAPI
I hope that after I can get a good explanation of this, to write it in the documentation of stackoverflow to help others.
There are so many approaches to this and there is not a single correct answer to your question.
Basically, the models you use in your views should not be the ones, that you persist in your database. Therefore, what you can do for example, is create a 'service' layer, so controllers operate on services, and services operate on repositories. This way you achieve a clear separation of concerns between each 'layer'.
First of all, keep persistance models and business logic out of controller. The only logic that belongs to a controller is application logic.
Secondly, introduce business logic layer (AKA. services layer), in which your business logic belongs. You can also create separate models in that layer, so your controllers do not operate on the models that represent your database entities, and you just apply mappings between models that services expose to your controllers and models that they pass to the repositories. Take those services as dependencies to your controllers. Your services will also take your repositories as their dependencies.
This way your controller has no idea what your business logic is - it only knows that it has to call some service which takes care of everything. Your service has no idea about where it's being used, he knows nothing of controllers, views or the way your data is presisted in the database - it just executes your business logic. And your repositories just persist your entity in storage of your choice, they only know their entity model and how to persist it. They haven no knowledge that there are services, controllers or views. The benefit which you get from is that when you decide to change your code, whether it's the business-validation logic of minimum allowed customer age or the mechanism or saving your entity, you are likely to do it in just one place in your code, place that is responsible for that specific thing.
Keep in mind that is the minimal separation of concerns between those components that you can do. Be aware that everything depends on your case and creating simple layers between presentatio, business logic and data persistance layers is not always the right or trivial thing to do, as it might sometimes be tricky not to leak your business logic into layers other than where they actually belong.

MVC: is there a definitive answer as to where business logic belongs? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm currently trying to refactor a C# MVC application in spite of having limited experience of the pattern. Reading around the subject, I seem to constantly blunder in to dimetric opposite opinions on best practice.
My biggest problem is that there's way too much stuff in the controllers. They work, but they're full of business logic which is hard to restructure and to test. Models are mostly just thin DTOs. So, where do I start putting this useful business logic in order to rework it and test it?
A lot of people say it should go in the model. But then you get some people saying it should go in the controller after all. And other people telling you that the principle of the model containing data and NOTHING ELSE is fundamental to the pattern.
Then you get people telling you it should go in a fourth type of class, a ViewModel. Now I've worked on MVVM in WPF and I'm familiar with this paradigm. But adding it to MVC just seems to replicate a lot of work that's done elsewhere, for no better reason than blindly following a pattern dictate.
Yet another option is to put it in some sort of helper class. This seems a common suggestion, which I won't link. But doing that seems a wasteful use of another class which has no point to exist outside of providing functions to a single controller. And that would seem a fundamental violation of OOP principles.
Is there a definitive "correct" answer to this? If so, why is there so much confusion? If not, how do you go about gauging the best solution in this morass of opinion?
To me, the M in MVC stands for view model, it contains the data needed for the view to do its work, so that the view can remain as dumb as possible.
This view model is created in the controller and passed to the view, but as you said, the controller logic should be kept small - so no business logic here.
This business logic belongs in services - which could be remote services exposed with WCF, or a web API, or just a class library with methods in your web site.
So, summarized:
the controller calls the services to get data in the form of a model. Business logic is inside these services, the model returned is just POCO.
the controller creates a view model based on the received model, which contains the properties in the format which is best for the view.
the controller passes the view model to the view, which uses the view model to build itself.
I don't believe there is a definitive "correct" answer. I believe it's all in preference and how complex your data manipulation is.
At my company we use helper classes/a service for the purpose of organization. Our controllers do not contain any functionality except for taking in a model, manipulating it, and spitting it back to the view.
We have a vast amount of data manipulation, and to do that in the controller would be a horrible mess.
Most people would agree that no logic should be in the controller. The difference is where that logic should be. For my company, it would have been ridiculous to put it in the models themselves because of the sheer volume of manipulation that takes place. If there isn't a large amount of manipulation I would put it in the models.
On the project I am currently working on, we have kept our Controllers reasonably free of Business Logic as we have separated them out into Units of Work. I believe this pattern was adopted to allow us to swap the Units of Work in and out depending on the client etc.
Where as the previous project I worked on was all in the controllers and broken down into smaller shared helpers where necessary.
I don't think there is strictly a correct way or an incorrect way. The majority of the time it seems to be down to personal preference of the developer.

MVVM pattern necessarily needs a database? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
MVVM pattern necessarily needs a database? Because, all crud examples that I found do not use a database, they all do the CRUD inside the code, with list's and obsservableCollection's.
Thanks
The answer to your question is no. The MVVM design pattern is a presentation model hence independent from a persistent data store. Consequently, you do not need a database. Read this for an introduction: WPF Apps With The Model-View-ViewModel Design Pattern and Wikipedia.
What you do need though is a data model which forms part of the MVVM design pattern. The decision to use a database (or any other datastore) for CRUD operations of your data model (or parts of it) depends on the functional requirements of the application.
No, MVVM Pattern is just a pattern(a reusable solution for a recurring problem). So it is an application necessity whether to have DAL(data access layer) or not.
MVVM consists three layers:
1. Model 2. ViewModel. 3. View
MVVM is short for Model-View-ViewModel.
Models are simple objects of classes that hold data( For example, Person, Animal or Tank classes). These classes should only contain properties and property validation. There are no responsibility for getting data, saving data, click events, complex calculations, business rules, or any of that stuff.
Views are the UI used to display data, what user see and what user interact with. In most cases, they can be DataTemplates which is simply a template that tells the application how to display a class. It is OK to put code behind your view IF that code is related to the View only, such as setting focus or running animations.
ViewModels are classes where the magic happens. They send data to View by events(INotifyPropertyChanged). This is where the majority of your code-behind goes: data access, click events, complex calculations, business rules validation, etc. They are typically built to reflect a View. For example, if a View contains a ListBox of objects, a Selected object, and a Save button, the ViewModel will have an ObservableCollection ObectList, Model SelectedObject, and ICommand SaveCommand.
MVVM Pattern allows you separate data from view. Data is just data and view is just view. No dependency between data and view, so we have other advantages such as unit testing and loose coupling.

Correct Approach of following MVC [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am working in MVC from last one year. I am following the MVC approach i.e simple appraoch and not Repository patterns. Now, I come to know about the advantages of using Repository with dependency injection and I feel it follows the oops in right way.
That is my thinking.
In one of my sample/test project I started working with repositor and have few questions about it:::
1) when we use EDMX , suppose I have a table names "Users", it automattically
creates a class named as "users" which contains all the fields as properties.
What I usually follow is I create a model layer and add a class in that model layer of name
"myUsers" that will contains same properties as the class users have.Now, I will bind the view
page with "myUsers" so that it cannot deal directly with DAL.
and Whenever I post something from my view page , the object comes in "MyUsers" model,
and here I again do something like this.
Users=MyUsers(I do this by doing this for each property like::
Users.Name=MyUsers.Name
and then I save it in Database.
I use above approach and in my applications I have used the above approach.
Now my question is
Can I bind my view page directly with "Users" class? As I see some applications,
it is happening. It reduced much work and also overheads in application.
What is correct approach ? to deal directly with DAL or there should be models
in between them?
"Correct approach" is subjective. We like to create ViewModels that exist purely to show domain objects in a view because it means we can separate view logic from the domain. We may not always want to show / load every property of a domain object. As another example, we put DataAnnotations attributes for validation on our ViewModels.. but we leave the domain objects as nice little POCO's.
Manually mapping them like you are is an incredible waste of time though. There are frameworks that do that for you.. such as:
Automapper
ValueInjector
According to me, this is the correct architecture.
Let me explain the answer in comments below.

.Net MVC - Accessing the Database from within a View more than just Bad Practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've seen a few developers instantiate models that access the database from within a view. Typically they do this when they want to access an html partial and they just create a new viewmodel right there in the view :
<div class='blogListing'>
#Html.Partial("BlogListing", new BlogListingViewModel(10));
</div>
To me, best practice would be to instantiate all of your models inside your ViewModels, then pass them to your partials. In the example below, BlogHomeViewModel would create a new BlogListingViewModel(10) and set it as a public property for the View to consume :
#Model BlogHomeViewModel
<div class='blogListing'>
#Html.Partial("BlogListing", Model.BlogListing);
</div>
My question is, is this more than just a bad practice / maintenance issue? Are there also performance concerns for accessing a database from within a View? I would think a model would be able to fire off all of the database requests at about the same time, but within a View you're already starting to render html, and thus must open and close more connections,slowing down page load. Am I off-base here?
As always, there's more than one way to skin a programmer. That's how that saying goes, right?
Years ago when I first started using a MVC framework I kept trying to figure out what the gold standard was for what each letter should be responsible for. There's a lot of opinions, but ultimately it's up to you and your team to figure out what works for you.
I would argue that connecting to the database within your view or model is bad practice. Some people open connections within their models to pull in data. Not me. When I think about what a model is responsible for it's simply:
The data that will end up in display in the UI
The data that is needed to properly build the UI (e.g. a bool for conditionally showing some options)
I will often refer to my models as "self-sufficient". What that means is my models need to have all the data required by the time it hits the view. I let my controller handle database connections, API calls, LDAP queries and so on. Obviously my controller doesn't contain all of the code for those methods (I have proper specialized libraries for handling different requirements), but, it is the broker between the different sources of data.
What's nice about architecting your applications in this fashion is that you are certain when your heavy lifting is done. You know that when you call return View(model) that you have all the data that you need. You don't have to troubleshoot bad queries (or slow API calls, etc) from your model or view. Having that line drawn as to what each piece is responsible for is what makes the framework useful to me.
Remember, these are my opinions on how the framework should be used. I'm not saying it's the only solution. Your development team might find something more useful, but, keeping this discipline has been working well for me for a handful of years.
The unwritten rule to not access the database from the view is not really about anything other than writing good maintainable code. Developers are always looking for some concrete validation for doing something: it's more performant, etc. Sometimes, you just do things because it won't make the developer that comes after you, well, want to come after you... with a butcher knife.
The whole purpose of MVC (the paradigm, in general) is separation of concerns and proper modularization of code. If you view needs to know how to access the database, you've broken the single-responsibility principle and tied your code in knots, where if database access changes, you need to change the view as well. That's not exactly common sense, so any developer unfamiliar with the codebase can (and Murphy says definitely will) come along and change something that affects that code in the view, without knowing that they affected the view, and your application goes down in flames.
I don't believe there would be any performance issues from calling the DB from your view. It all get processed in IIS anyways before it ever hits the browser. The only exception would be if you are opening/closing connections multiple times.
Typically, the main reason to keep the seperation of concerns is so that each part of the M V C has a specific duty and you aren't looking all over to figure out just where this data came from.
Also, from a unit testing standpoint, you'd want to keep your data access in a place where it could be tested, and the view isn't a very good place for that.

Categories