understanding MVC in simple words - asp.net-mvc

i checked google, books etc but all defines it differently and made me highly confused. Please describe it simply that what parts does what and contains what or can ?

lets start with
CONTROLLER:
MVC always start with the CONTROLLER. its connects your VIEW and your MODEL. CONTROLLERS are responsible for your business logic like validation, computations, etc.
MODEL:
responsible for obtaining/storing data in your database.
VIEW:
displays data, your User interface.

The Model-View-Controller as it implies contains three components when
this model is implemented:
The Model - This should take care of all the operations which deal
with the data required (in other words the business logic) for the
application, which is implementing the MVC model from now onwards will
be referred to as by the MVC application. The operations can mean
reading, writing data into the database, getting information from
remote machines via network, time consuming operations etc. The model
should also inform the view about any changes to the data happening in
the background. The View - This component takes care of presenting the
data to the user. With respect to the context of this article, i.e.,
WinForms, the view class will be tied around with the Form which will
be shown to the user. The Controller - This is the center and
important component of the MVC pattern as it ties the Model and View
together. The Model which manipulates the data and the View which
presents the data to the user does not know the existence of each
other or they interact directly with each other. It is the controller
which acts as an intermediary and ties them together. For example, the
controller takes the input from the user such as a button click and
informs the model to take appropriate action, if there should be an
action that needs to be initiated to manipulate the project data.
Check here

The View is the parts of the application that handles the display of the data.
You can say it GUI of your web application. It donot have any logic say database conenction logic.For example , if you want to display list of students from the DB , one way is put the select query in the .asp.,.cshtml,.vbhtml file and show the reult there . But in MVC view will have code of displaying recodes and model will have the code fore retriving it. Most often the views are created from the model data.
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
It connect the view to model , model to view and user request for some page to view.
When user enter the url like ".../Home/Index" then it goes to the Controller first . There can be many controllers , here it will go to "Home" controller class and in that class it will call the "Index" action or say "method". That method will return the "Index.cshtml/Index.vbhtml/Index.asp" view back to user as response.
MVC seperate tha main logic from the view and controller is the one who handel those.

Related

mvc architecture ruby on rails

In Ruby on Rails, MVC architecture is designed in such a way that, the controller will receive the request and talk to model to receive data and again controller will talk to view to generate html. Now my doubt is, why should model reply to controller and then controller to view, rather than model directly replying to view to generate html. Why was it not designed in that way?
Can someone please clarify? Thanks in advance.
... model directly replying to view to generate html ...
And what if tomorrow you need to generate JSON? And then XML? And other 10 formats? Will you update model each time?
Model, View and Controller have distinct responsibilities.
Model - business logic. Saves and loads data.
View - renders data in a specific format.
Controller - mediator between the two. Parses requests, does authentication/authorization, asks model for data, calls appropriate view with that data.
There should be no business logic in views, rendering in models, etc. This helps for better, cleaner code.
In my hypothetical example, you just need to add a view that can render JSON representation of data. And, probably, add one or two lines to controller (often you don't have to). Model is left unchanged. Its concern is data persistence, not data presentation.

Is it considered bad practice to write db queries in a controller rather than a model

I've read that best practice dictates fats models, skinny controllers.
Models should contain business logic such as getting a list of customers based on parameters sent from a controller.
Controllers should contain just enough logic to invoke methods within a model to return to a view.
However I see many examples and tutorials where there is logic within the controller such as a query that accesses a db to get a list of products. I was under the impression that the logic should live in a method inside a model. The controller can then invoke this method, rather than containing the actual logic to query the database.
So if I have a ProductController I might have a Index action which returns an Index View, and I would have a ProductModel which would house my logic to display certain products based on a query string(which the ProductController would pass to said model). Right?
So if I have a ProductController I might have a Index action which returns an Index View, and I would have a ProductModel which would house my logic to display certain products based on a query string(which the ProductController would pass to said model). Right?
That is correct. As per the Model-view-controller architecture:
The model manages the behavior and data of the application domain,
responds to requests for information about its state (usually from the
view), and responds to instructions to change state (usually from the
controller). In event-driven systems, the model notifies observers
(usually views) when the information changes so that they can react.
The view renders the model into a form suitable for interaction,
typically a user interface element. Multiple views can exist for a
single model for different purposes. A viewport typically has a one to
one correspondence with a display surface and knows how to render to
it.
The controller receives user input and initiates a response by making
calls on model objects. A controller accepts input from the user and
instructs the model and viewport to perform actions based on that
input.
Keep the data-related queries and operations in the model; stuff as much as you can in there in accordance with DRY (Don't Repeat Yourself). Make the functions reusable as much as possible so they can be ported into various controllers and used throughout the application as necessary.
The view should contain little - if any - logic outside of view-specific work.
Your controller functions should invoke the model functions required to retrieve and manipulate data, and should be as "thin" as possible (as you pointed out). The smaller and less involved the controller, the easier it will be to add asynchronous features that "don't reboot the application" on the front-end, making for a better user experience. (If you are concerned about this, anyway!)
The Add Controller dialog box in VS 2010 has the option of adding a scaffold with CRUD functions into the controller. This should tell you quite a bit above how the ASP.NET MVC dev. team views this debate.

MVC: I need to understand the Model

I've been working with the MVC pattern for a while now, but I honestly don't feel like I truly understand how to work with and apply the "Model" ... I mean, one could easily get away with using only the Controller and View and be just fine.
I understand the concept of the Model, but I just don't feel comfortable applying it within the pattern... I use the MVC pattern within .NET and also Wheels for ColdFusion.
"the Model represents the information (the data) of the application and the business rules used to manipulate the data" - yes, I get that... but I just don't really understand how to apply that. It's easier to route calls to the Controller and have the Controller call the database, organize the data and then make it available to the View. I hope someone understands where my confusion resides...
I appreciate your help in advance!
Look at it like this. When your client requests a page this is what happens (massively trimmed):
He ends up at your controller
The controller gets the necessary data from your model
The controller then passes the data to the view which will create your HTML
The controller sends the HTML back to the client
So client -> controller -> model -> controller -> view -> controller -> client
So what is the model? It is everything that is required to get the data required for you view!
It is services
It is data access
It is queries
It is object mapping
It is critical 'throw exception' style validation
Your controller should not be writing your queries if you are sticking to the pattern. Your controller should be getting the correct data required to render the correct view.
It is acceptable for your controller to do a few other things such as validating posted data or some if/else logic but not querying data - merely calling services (in your model area) to get the data required for your view.
I suppose it's just what you decide to call the different bits in your application. Whichever class you use to pass information from the Controller to the View can be seen as/called "The Model".
Typically we call Model our entity classes, and we call View Model the "helper" classes, for lack of a better word, we use when a "pure" entity (i.e., one that will be stored in the database) doesn't suffice to display all the information we need in a View, but it is all mostly a naming thing.
Your model classes shouldn't have any functions; ideally a model class will have only properties. You should see model classes as data containers, information transporters. Other than that they are (mainly) "dumb" objects:
// This would be a model class representing a User
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
How do you actually pass information (whatever that might mean in your context) form your controller to your View and vice versa? Well then, that's your model. :)
Here is the way I have explained before:
Controller: determines what files get executed, included, etc and passes user input (if any exists) to those files.
View: anything that is used to display output to user.
Model: everything else.
Hope that helps.
Model is the code representation of your base Objects. While some less data-intensive systems may be light on the model end of MVC, I am sure you will always find an applicable use.
Let's take a contrived (but realistic) example to the usefulness of a model:
Say I am making a Blog. My Blog has Post objects. Now, Posts are used in and around the site, and are added by many users in the system. Our system was coded for people to enter HTML into their posts, but low and behold, people are starting to add pasted text. This text uses "\n" as the newline character.
With a model, this is a relatively simple fix. We simply make a getter that overrides postText:
public function get postText() {
return this.postText.replace("\n", "<br />");
}
Suddenly, we can affect behavior across the entire site with a few lines of simple code. Without the implementation of a model, we would need to find and add similar functionality where ever postText is used.
The Model in MVC is all about encapsulation and flexibility of a codebase as it evolves over time. The more you work with it and think about it in this manner, the more you will discover other cases that would have been a nightmare otherwise.
--EDIT (you have added to your question above):
Let us take this same example and use your Controller calling the database. We have 9 Controller classes for vaious pages/systems that use Post objects. It is decided that our Post table needs to now have a delete_fl. We no longer want to load posts with delete_fl = 1.
With our Post model properly implemented, we simply edit the loadPosts() method, instead of hunting down all the cases across the site.
An important realization is that in any major system, the Model is more of a collection of files than a single monolith. Typically you will have a Model file for each of your database tables. User, Post, etc.
model: word, sentence, paragraph
controller: for (word in sentence), blah blah... return paragraph
view: <div>paragraph.text</div>
The idea is to separate the concerns. Why not just have the controller logic in the view as well? The model represents the business objects, the controller manipulates those objects to perform some kind of task and the view presents the result. That way, you can swap an entire view for a different one and you don't have to rewrite the entire application. You can also have people work on different layers (model, controller, view) without affecting the other layers to a significant degree.
By combining the controller and the model, you are making your code less maintainable and extensible. You are basically not performing object-oriented programming as you are not representing the things in your database as objects, you are just taking the data out and sending it to the view.
The model contains business logic (i.e. significant algorithms) and persistence interaction - usually with a database. The controller is the MVC framework: Wheels, Struts, .NET's MVC approach. The view displays data that the controller retrieves from the model.
The big idea going on with MVC is that the view and model should be unaware of the controller - i.e. no coupling. In practice there's at least some coupling that goes on, but when well done should be minimal, such that it allows for changing the controller with low effort.
So what should be happening is a request hits the controller, typically a front controller, where there should be some glue code that you've written that either extends some controller object or follows some naming convention. This glue code has the responsibility for calling methods on the correct service layer object(s), packing that data inside of some sort of helper - typically an Event object - and sending that to the correct view. The view then unpacks data from the Event object and displays accordingly.
And when done well, this leads to a domain model (a.k.a. model) that is unit testable. The reason for this is that you've divorced the algorithms from any framework or view dependencies. Such that you can validate those independently.

Synthesize multiple action methods in MVC

We have a dashboard-style application with lots of individual bits of the screen that load asynchronously. Each of these bits really makes sense as its own action on the page's controller. However, the data will load more quickly if we reduce the number of http requests to 1. I'm considering creating an action that just returns a combination of results from several smaller actions, such that the web client can GET the actions separately or together. However, this seems like a hand-rolled solution to a common problem, so I'm wondering if there's built-in support for agglomerating actions in this way that I don't know about. Anybody?
In your core view, you can use the Html.RenderAction() method to render completely separate actions from another action.
Why don't you just use ViewModel containing all data needed for your dashboard and then create several partial views, feed them with data from ViewModel?
I have also an dashboard in my project, I did it this way and I am happy with the solution. I have DashboardController and its Index action just takes ViewModel (which aggregates all necesary data) and sends it to View. In that View, I have several partial views (each of them needs its own model) and I pass them data from my ViewModel. Inside that partial view are then references to specific actions (like CRUD for specific models).
When you do it this way, you can easily create partial views for specific models (Task, Project, User .. in my case). And then just use them as a pieces in your final layout. My ViewModel contains collections of Tasks, Projects and Users which I then simply pass to matching partial views.

Displaying and updating multiple models in one view

I have 3 different models, business_info, business_hours, business_vacations.
I have one view that displays all that information, so I made a new controller called business_all to gather all that info.
But when it comes to editing the individual parts within the page I'll be calling each of those 3 individual controllers to update, delete etc, then send back the updated data for that particular model.
Given that, should I skip having the business_all controller and instead, when the view is loaded have 3 ajax calls to each controller to get the relevant info?
one alternative is to make a non persisting model called business_all that has fields that combine the three models with its own validation and so on. and when persisting it actually saves to the actual models.
this way doing the forms and so on are easier as you can do form_for (BusinessAll.new ... ...) and so on.

Resources