I have an existing application with a datalayer (primary EF4), a businesslayer (custom code) and a windows application - now I want to create a webapplication using ASP.NET MVC but I am not sure exactly what to do especially in my models.
When my data and business logic already exist how should I structure my Models and Controllers compared to a referenceproject like MVC Music Store v2.0 (http://mvcmusicstore.codeplex.com/)? All my entities are stored in my datalayer and all my methods and logic are stored in my businesslayer so I guess I need no Models (unless I need specific web Models) and I guess my controllers will only need to call the methods in my businesslayer as I would to in a normal webform application?
Another question, if I need to display 2 lists with data from 2 different entities on 1 page I guess I need to create af Model with 2 properties (one for each entity)?
The last one for now, if, for some reason, e.g. a Get method from my businesslayer returns an exception how should this be handled in my Controller/View?
It depends on the complexity of your application. I would at the very least introduce ViewModels for each view so you can supply the view with the data that is required. If your application is light weight it might be fine to use your business layer in the controller. However, you might want to introduce a service layer that interacts with your business layer just to keep the controllers thin.
As for exception handling, you might want to look into the HandleError attribute.
Related
Is it a good practice to use Spring Controller class(with #ModelAttribute) and the jsp to prepare model at the same time or the model has to be prepared only by Spring and the view from the jsp?
The idea comes from this topic . I have a Controller class:
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, params = "mode=create")
public ModelAndView showCreatePage(#ModelAttribute("createForm") ApplicationCreateForm form)
{
return customMethod("some string");
}
and in my jsp I have:
<jsp:useBean id="createForm" scope="request" class="com.example.ApplicationCreateForm"/>
I do not need to populate the form with the information to be present to the user all fields are empty.
So from what I uderstand I have been declared ApplicationCreateForm bean twice, with the same scope - request.
Is it a good design practice to use both at the same time? Is there a reason for that? Does the second declaration(in jsp) give me more power, for example to override the model or it is complete unnecessary? Does the second declaration overrides the first one when both are present?
There are many things wrong with this implementation.
Is it MVC?
If JSP know about Model, why do we need controller. Lets remove the routing engine and use JSP directly to consume Model. But then the application will be monolithic. I believe you do not want that. We have two major flavours of MVC. In both, controller is the front facing object. It receives the command, interprets it, works with data layer and gets Model. If required the Model gets converted into a viewModel and then this object is passed to the view.
Why viewModel?
Say we are implementing paging on screen. We are showing list of persons. Person is your model here but your view also need to know page number, page size etc. Your model thus may not fit directly in this case.
Say we need data from multiple tables to shown on screen. This data is related in some way. Now will you pass separate model objects to view and let it do all the business logic? Ideally no.
Should not the design support DTO or ViewModel or Commands and Queries?
We want our application to be designed properly. As stated above we need to send data to view or clients (REST) after processing. Processed data may not map to you domain until unless we are just creating a CRUD stuff. What if you want to implement CQS or CQRS?
Where is separation, where is SOLID?
If my view is performing business logic then where is 'S'? If view knows about model and need to be changed in slightest of changes in model then where is 'O'?What if I want to separate queries from command (CQS) and scale the two things separately?
To conclude I would say, yes you can do this but it is not good if you are developing a decent size application or you think it will eventually be one. I have seen people using model entities starting from ORM, to controller to view. It will work but the question is do you want a monolithic and tightly coupled application. As per my experience the presentation logic (view) has very different logic and need of data in comparison of controller and same goes for your data access layer.
I think you should prepare your model fully in spring controller. Then view should be as passive as possible, ie. only showing model attributes received from controller while having no further knowledge about application logic. This approach gives you clean separation of concerns and you view is as independent as possible and can be easily switched for different view technology - eg. thymeleaf or freemarker templates. The whole idea of MVC is to separate presentation layer and by leaking business logic to view you create unnecessary dependencies.
Your view should be as simple as possible, as the logic leaked to view makes it very hard to test and reuse. On the other hand, if your logic is nicely separated, you can test it easily and reuse it easily. Ideally, business logic should be completly independent on web environment.
By defining you are creating tight coupling between your view and class com.example.ApplicationCreateForm, using spring mvc you achive loose coupling between your controllers, view and model it might happen that you change you model name but you still have same properties in it which might be enough for view, in above case you will need to update your view but it won't be required in case you are using Spring MVC.
Since spring comes with the concept of making things loosely coupled to make your code more testable, you should always keep in mind that separation of concern is your priority. So it is always the best practice to prepare your model fully in Controller, not in views.
Keep thing simple , make your controller responsible for preparing your model, and keep your views to display the model only.
So, a big NO to your question. The second declaration isn't going to make you powerful, rather help you to be tied up.
I have to gradually replace an ASP.NET Web Forms application with an ASP.NET MVC3 layered application. Let's take into consideration just the Repository layer.
In my new MVC application I have one project for Data (name MVC.Data) and one for Web.
In the MVC.Data I have an edmx file with the EF classes, which models just the DB table (no views), and a Respository class myRepository which provides methods that perform simple queries.
In the old Web Forms application I have a GridView which is filled using as DataSource an SQL database view.
In order to have the same result in my new MVC3 application, I have two options:
1) Create a Service layer (and project MVC.Services), where I have a method that fill a new class myViewClass which contains all the fields of the SQL DB view and give it to the controller.
2) Create a class within the MVC.Data project which is directly filled by its constructor by using LINQ statements directly against the EF classes.
I read about the factory pattern and the 1st solution seems the most appropriate, however many people always suggest not to create a Service Layer if it is not needed. What is the best choice in this case?
Actually building the view model should be done in a mapping layer. Basically your controller action might look like this:
public ActionResult Index()
{
SomeDomainModel model = repository.GetSomeDomainModel();
SomeViewModel vm = Mapper.Map<SomeDomainModel, SomeViewModel>(model);
return View(vm);
}
The view model is defined in the MVC project as it is a class that is specifically designed to meet the requirements of the given view.
The Mapper.Map<TSource, TDest> method I have shown in my answer comes from AutoMapper which I use in my project but you could define any custom mapping layer you like.
The mapping layer must also be part of the MVC project as it must be aware of both your domain models and your view models in order to perform the mapping.
As far as the service layer is concerned, you could use one when you have some complex business operations which could be composed of multiple simple repository calls. But some might argue for the existence of a service layer at all. I think that both approaches have their pros and cons that must be evaluated when designing a system and most importantly take into consideration the specific context and scenario you are designing.
So I did some Google searching on the MVC pattern and I'm still not exactly sure what the "Model" part is. What exactly does it deal with? I'm rather new to programming so all the explanations I can find go right over my head. I'd really appreciate it if you could give me an explanation in simple terms.
Thanks
The simplest way I can describe it is to call it the "Data" part. If it has to deal with getting or saving data, it's in the model. If you have a web application, the model is usually where you interact with a database or a filesystem.
Model in MVC is a place where data presented by the UI is located. Therefore, it shouldn't be confused with Domain Model which serves as a skeleton that holds the business logic.
Certainly, for a small application that serves as a service for CRUD operations backed by a database these two models can be the same. In a real world application they should be cleanly separated.
Controller is the one who talks to the application services and the Domain Model. It receives updates back from application services updating the Model which is then rendered by the View.
View renders the state hold by the Model, interprets User's input and it redirects it to the Controller. Controller then decides if the Model is going to be updated immediately or first the information is forwarded to application services.
The Model can represent your "Domain Model" in smaller projects. The Domain Model consists of classes which represent the real-world entities of the problem you're dealing with.
In larger projects, the Domain Model should be separated out of the actual MVC application, and given it's own project/assembly. In these larger projects, reserve the "Model" (i.e. the "Models folder in the MVC project") for UI presentation objects (DTOs - Data Transfer Objects)
The model is respomnsible for managing the data in the application. This might include stuff like database queries and file IO.
the view is obviously the template, with controller being the business logic.
The model is used to represent the data you are working with. The controller controls the data flow and actions that can be taken with the data. The view(s) visualize the data and the actions that can be requested of the controller.
Simple example:
A car is a model, it has properties that represent a car (wheels, engine, etc).
The controller defines the actions that can be taken on the car: view, edit, create, or even actions like buy and sell.
The controller passes the data to a view which both displays the data and sometimes lets the user take action on that data. However, the requested action is actually handled by the controller.
I wanna restrict model to calling to db only
while controller will call model, libraries or helpers.
I do not want to put logic in controller nor in the model to prepare data for views.
Now the logic for preparing all the arrays for views are done in controller. I am creating a library to separate this part as sometimes i feel it is overloading the controller
Hence, i want to create a library class and make controller build the view data before throwing it to the view. It is not exactly templating.
The thing is i do not know how to name it.. Any good suggestion ?
I am thinking view_builder, ui_builder, ui_components?
Cheers
Here's how I'd layer the app:
View
Controller
Service
Persistence
View is either desktop or browser or mobile-based.
Controller is tightly bound to view. It's responsible for validating and binding input to model objects, calling services to fulfill use cases, and routing the response to the next view.
Services fulfill use cases. They know about units of work, own transactions, and manage connections to resources like databases. They work with model objects, other services, and persistence objects. They're interface-based objects, but can be remoted or exposed as web services - RPC-XML, SOAP, REST or other.
Persistence is another interfaced-based object. The implementation can be relational or NoSQL; the important thing is that the interface expresses CRUD operations for model objects. If you use generics, it's possible to write one interface that works for all.
I wouldn't have model objects persist themselves. I'm aware of the "anemic domain model" pejorative, but I think more exciting behavior should center around the business purpose, not CRUD operations.
Good setup. I also sometimes use CI libraries to work out the kinks in a returned data array before passing it to a view. I also sometimes just use the model.
And good for you for thinking about names - I think all the ones you mention are fine; you could also think about naming your library something like data_structure or array_to_object - or something more specific to your own problem like friend_map or tag_cloud.
My advice: pick a name, and then don't be afraid to change it if something more descriptive comes along or the function of your library evolves into something else. Find+replace is your friend.
I've done a fair amount of work on MVC on the web, and we're learning about it in my OOP class. I'm seeing some differences, and I can't tell whether that's because the Web's version of the MVC pattern is different than the traditional one, or whether I misunderstood it.
From my understanding, The model (your flat files, RDBMS', etc) is a generic data-housing object. The View (Browser, HTML, etc) is what the user interacts with, and the controller mediates between the users actions and the data. The controller is the most domain-specific part, and it manages the views, tells the model what it needs, and tells the views what to display.
In class, we have the Views matching what I just described, the Model contains a list of the views so that it can update them when the data changes, and the controller simply maps the user's actions to calls to the model and to specific objects (which may themselves, ask the model to update the views). What ends up happening is that most of the business logic is in the model, and it's tied very heavily to the simulation or application that is being written, while the Controller is reduced to a mapping tool between commands and methods.
What are your thoughts on this?
In a non-web interface the controller handles the inputs from things like the keyboard and mouse, choosing which views to render and what changes to make in the model based on those inputs. The view and model can be more closely related because the view can register callbacks directly with the model entities to be notified of changes and thus be updated based on changes to the model directly instead of being updated by the controller.
In the web world, views are necessarily more decoupled from the model. It must act through the controller actions because it has no direct access (after being rendered and delivered to the browser) to the model. The controller takes a larger role in this environment even though the only "input" it has to deal with are browser requests. In a sense, the coupling that used to occur with the view in non-web MVC is transferred to the controller acting on its behalf. Since there are no callbacks from the model to respond to (let's forget about "push" technologies for now), more business code is incorporated into the controller since it's the natural place to model business processes, though perhaps not validation.
In my understanding controllers in the web MVC pattern are just bridges between Models and Views, they simply grab the data from the Model and pass it on to the View. The Model and the View and independent and never talk to each other.