As I've been reading this article: http://www.codeproject.com/Articles/42830/Model-View-Controller-Model-View-Presenter-and-Mod, MVC was explained like this:
In this diagram, View-Model is observer pattern where any changes in Model notify View's Update method to update the states of Views and passing its current state to these Views.
Relation between Views and Controllers are defined in Strategy Pattern where Views get concrete controllers and run the algorithms in controllers as defined by Strategy Pattern.
So Controllers update models and models notifies views to update their states.
However, for some reason I couldn't visualize the same logic for Asp.Net MVC as Controllers have access to Model and pass these models to Views but views uses Models directly to get their properties,etc to update their states but I couldn't fit the observer pattern between Views and Models in Asp.Net MVC.
Could some one please explain what I am missing out?
ASP.NET MVC upholds the stateless nature of the web, so once a view is rendered there is no way for the controller to know about changes to an instance of a model object.
This is different to a stateful platform like Silverlight or WPF. The fact that they're stateful allows a controller (or ViewModel if you're using MVVM) to observe what's happening on the UI, make changes to model objects, and then have the view update itself accordingly.
In ASP.NET MVC when data gets passed from the controller to the view, it's a one-way trip. There's no equivalent of the View.Update() method; the view gets rendered once and then that's it. There's also no way for a view to call back to a controller, as per Controller.AlgorithmInterface. You can achieve something similar with an AJAX callback but then you'll have to use some behind-the-scenes magic to repopulate the controller with the state data (e.g. by passing an object ID from the view back to the controller).
Related
I start learning asp.net core
and see that in the views file < razor pages > you always can using object #Model of ViewModel class in your view,
What I want to know that is kind of architecture pattern use here, is MVC or MVVM?
From your description, I assume you want to know, whether the Asp.net Core Razor page's page model is an MVC architecture pattern or MVVM pattern, right? I suggest you could check this article.
The main purpose of the Razor Pages PageModel class is to provide clear separation between the UI layer (the .cshtml view file) and processing logic for the page.
A View Model is an implementation of the Presentation Model design pattern. It is a self-contained class that represents the data and behaviour of a specific "view" or page. The view model pattern is used extensively in MVC application development, where it mainly represents data, but typically little behaviour. In Razor Pages, the PageModel is also the view model.
Razor Pages is sometimes described as implementing the MVVM (Model, View ViewModel) pattern. It doesn't. The MVVM pattern is applied to applications where the presentation and model share the same layer. It is popular in WPF, mobile application development, and some JavaScript libraries. A main feature of MVVM is that the view is updated automatically to reflect changes to the underlying model. This process is usually controlled by two way binding and an implementation of the Observer pattern. In a server-side web application, the model resides on the server and the view is on the client. You need to implement additional complicated layers to achieve anything like the Observer pattern in such a distributed architecture.
I have gone through some answers here and and some articles on MVC but I still have a confusion regarding the role of a Controller in a MVC application.
I read in a book that the Model is self-contained and functions independent of View and Controller. And that the Model contains the business logic and data access codes. Source
Also in the best answer
here
What goes into the "Controller" in "MVC"?
But the other answers around here say that it is the Controller that represent the business logic
Where can I find a dead-simple explanation of MVC?
So which is the correct answer?
Wikipedia states very simply: The controller, accepts input and converts it to commands for the model or view.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
This answer is correct
Model: This component represents the data and the business logic of the application.The model in the MVC framework is not related to the presentation of the application.The model component focus on keeping track of the state of the application.It also defines business rules for data, means how the data can be changed and manipulated.
View: The view provides the user interface (UI) for the model. The main work (function) of the view represents the information in user understandable format. It uses UI Components such as HTML,CSS,Jquery etc.
Controller: Controller act as a mediator between view and model. it is responsible to control the data transmission between the model and the view. It maps the user action into model updates.The controller layer is helpful to select the most appropriate view and delivers it to the user.
Actually, The Controllers are mediater between the view and model. they don't define the business logic. Models are responsible for business logic.
Controller acts as a mediator between the View and the Model class. It is used just to remove the dependency between model and view classes.
Kindly refer to this link..
https://www.tutorialspoint.com/mvc_framework/mvc_framework_controllers.html
The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.
The Controller class is responsible for the following processing stages:
Locating the appropriate action method to call and validating that it
can be called.
Getting the values to use as the action method's arguments.
Handling all errors that might occur during the execution of the action method.
Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).
Whenever I update an entity, I need to include every field in the form as a hidden input, so that it's value doesn't get set to null.
Setting the property as not modified, like the code below, prevent this. But this code is abstracted into a generic IRepository interface encapsulated by an UnitOfWork class, so I can't specify non-modified properties for each entity.
Entry(entry.Entity as MyModel).Property(e => e.AProperty).IsModified = false;
Is there another way to do that?
You could use a MVVM architectural pattern. The Model View ViewModel (MVVM) is an architectural pattern used in software engineering originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler.
Model : Model refers to your application data. In a real world ASP.NET web application, your data will typically be stored in a SQL Server database and your UI gets it from the server by making AJAX requests or some similar technique.
View Model : View Model refers to your data and UI level operations that you wish to perform on the data. The operations may include business validations or conditional checks or updating certain parts of the web page. You can think of View Model as a wrapper over your model data that adds UI level operations to it.
View : View is the user interface of your application. A View interacts with View Model to invoke some operations. A View is updated whenever data from the View Model changes. For a web application a view typically takes the form of an HTML document.
Here is a real world example using ASP.NET and EF. http://blog.tonysneed.com/2014/05/28/real-world-mvvm-with-entity-framework-and-asp-net-web-api/
I have developed a WPF-application. I have a mainwindow which inherit from Window, a tabcontrol and many tabitems in this tabcontrol which inherit from UserControl. Every tabitem has its own cs-file, where I code in C# all the businesslogic, and a XAML-file where the development of the UI is done. I also have a SQL Server with a database which i connect to trough LINQ.
So i have to write about my choice of which controller i use in my application. This is where i get confused, since i havent manually programmed a controller and i thought the ViewModel would behave like a controller in my case. Could this be correct? Can the ViewModel behave like a controller?
A controller can send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document). It can also send commands to the model to update the model's state (e.g., editing a document). Model_View_Controller
The viewmodel is a “model of the view” meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindings. It could be seen as a specialized aspect of what would be a controller (in the MVC pattern) that acts as a converter that changes model information into view information and passes commands from the view into the model. The view model exposes public properties, commands, and abstractions. Model_View_ViewModel
The introduction of MVVMC (MVC + MVVM) is nessesary in cases you would like to drive many similar pairs of View-ViewModel (use cases). You can then introduce controllers. Model_View_ViewModel_Controller
In the simplest case, have the ViewModel implement the "controller" logic. For large applications, I sometimes use an MVVMC pattern which uses a separate controller class. There has been a lot of recent support on the blogosphere for using MVVMC over MVVM.
MVVM is dead, long live MVVMC!
MVMMC – MVVM grows a Controller
We're working on some kind of Cloud CMS using ASP.NET MVC technology, and have found some obstacles on the way. There is a number of parameters user could change thru the control panel that we need to end up in Views. For example, Facebook application id to initialize the Facebook JS API. Or additional text to be shown on the page. Or background picture. For now we're not using DI to transfer this parameters, instead we're adding them to the ViewModel, but this ruin the ASP.NET MVC way of working with models (e.g. form validation, bindings etc.)
It looks like that using DI to inject services for providing parameters, texts and pictures could make my views less dependent on controllers specific, and there is even some Microsoft technique to do it http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-dependency-injection#Exercise2. However, there are a lot of answers on forums against injecting services into Views using DI.
So the question: what is a right way to inject some services into Views? Or I shouldn't do it at all and something is wrong in the application design?
UPDATE: some real code examples (now we're using Model to inject the services)
Injecting texts from database (they have to be user-editable, as it is CMS):
<div class="steps">#Html.Raw(Model.Texts["Main", "Step2"]</div>
Injecting translations from database (actually, it is localization):
<div class="gonfalon">#Model.Translations["Title_Winners"]</div>
Injecting parameters (from database, could be request-specific; for example, if the site has different domains, facebook application should be per-domain):
Facebook.Initialize(Model.Parameters["FbApplicationId"], Model.Parameters["FbApplicationSecret"]);
The problem of current approach is that this code has taken from contest mechanic. It is definitely out of contest business scope to deal with custom texts, translations or facebook application Id. Also it ruins the Model as model models not actual business domain but deals with a lot of things actually belongs to View (like translations and custom texts)
UPDATE 2: Have modified the snippet from the answer below to be a bit more generic:
public static class WebViewPageExtensions
{
public static I ResolveService<I>(this WebViewPage page)
{
return DependencyResolver.Current.GetService<I>();
}
}
No, you shouldn't inject services into Views, but...
For scenarios such as theming where you want to give the theme developer more power, just one model isn't enough. If your model contains the current post for example, how can a theme designer asks for a list of categories for the sidebar? Or for a widget?
In asp.net mvc you can use extension methods to offer that functionality.THe extension method will use the dependency resolver to get the service. This way, you can have the needed functionality in the view without actually injecting a service.
Note that calling the business layer to update the model is still a violation of Separation of Concerns. THe services made available to the view should contain only read model or general utility functionality.
An example
public static IMyViewServices MyServices(this WebViewPage view)
{
return DependencyResolver.Current.GetService<IMyViewServices>();
}
IMyViewServices lifetime configured in the DI Container should be per http (scope) request
No, end of story. Why? Here is why:
Your view only needs to know what the view model it's going to be working with to present that model. There are couple of reasons for this but the biggest one is the separation of concerns. Keep your view as stupid as possible. You will see that this seperation will give you a clean application structure throughout the way.
There is a number of parameters user could change through the control panel that we need to end up in Views.
I'm not sure what you exactly mean here but this is why there are view models. Your business layer will shape models up, your controller will simply map them to your view models and pass them into the view (presentation layer).
This really depends on how much or little you want your controllers to do and to what degree of separation you want to achieve.
In my world, the "controller" in an MVC app does as little as possible because I have a service layer handling all of the business logic and a data layer above that handling all of the database interaction.
On a GET, the controller will simply call a service method that will build the view model and hands it back to the controller and the controller passes it on to the view. On POST, the view posts data to the controller which sends it off to the service layer for validation, saving to DB, etc. The service is injected into the controller's constructor.
I'd be more than happy to post code examples if you'd like to see them.