I am creating an application using asp.net MVC. By default, the model, view and controller are all in the same project, but
can I create different projects or class library projects for the model, view and controller, so I could manage them separately? Is it recommended?
You definitely can. This part of the point of MVC to allow you to have such flexibility. As far as whether it is recommended, it depends on what you are doing. It is not necessity; however I think there are definitely many scenarios where it makes sense. Although, this probably makes the most sense for the model.
Related
I'm an ASP.NET MVC developer just starting with my first big project on rails however Im confused as where to put your business logic? on ASP.NET I create a library which contains services(Domain driven design) which handle business logic, I have heard that rails uses a concept of fat model skinny controller but I have some projects in ASP.NET which adding all the logic to the controller would create a big mess, is there any other way?
Go with the concept of FatModels and SkinnyControllers. Your models should know how they behave and what they should do.
When your models get too fat, extract them out into re-usuable modules and include them in your module.
Example of taking a fat controller (with logic) and moving to a model
Example of taking code from the views and moving into the model
You can easily test behavior of models using RSpec (or test/unit or shoulda). Then you can test that the application behaves correctly using Cucumber.
"Business Logic" or some might call it "Domain Logic" doesn't belong anywhere near Rails and/or your .NET MVC project. Rails and MVC should depend on your Domain not the other way around. I would recommend reading up on the Onion Architecture from Jeffery Palermo or watch "Architecture the Lost Years" by Robert Martin. (I think that's that talk anyway). There are probably more resources than that, but you'll thank yourself later for treating both Rails and .NET MVC like the 3rd party frameworks they are, and not the main house of your application.
I think this blog article provides a good overview of a strategy of incorporating domain driven design with in the rails framework: http://www.smashingboxes.com/domain-logic-in-rails/
TL;DR
Refactor your classic rails models into repositories, and use a facade layer in the controllers to interact with your domain model.
I'm struggling with this a little my self, and as much as the Fat Controller pattern seems to prevail, anything "fat" in software seems to be a smell, violating single responsibility.
You can put business logic anywhere you want (even in views! though that's a bad idea).
I'd say if the logic is tied to a real-world object, then put it on the model. Otherwise, use the controller. But it's up to you to determine how to do it for your app. Models are for modeling things, and Controllers are for controlling things.
Can someone help me understanding Model-View-Controller method to be implemented on WebForms? I am confused on couple of things:
If we have ABC.ASPX and ABC.CS files, what is view? is it only ABC.ASPX file? or combination of .ASPX + .CS file?
do we consider ABC.CS file as controller? If no, will it be a seperate class for controller?
Does database connection and data retreival go into Model or a seperate class which will be called by Model?
Can someone give a simple example for implementing Model-View-Controller in webforms?
Update
Hi guys, my question is how to implement Model-View-Controller methodology using WebForms not about ASP.NET MVC2.0. I apologise for the confusion.
Cheers
I guess I understood what you want to do: you want to implement a MVC architecture above an ASP.NET WebForms application. Fair enough.
All I can say is good luck! Me being there & done that. And how I regretted doing so... :P
Remember: ASP.NET WebForms is a huge abstraction, that tries to make the web into a statefull, event-based, windows-like environment, without any concern of decoupling whatsoever. So, trying to create an stateless, highly-decoupled and non-event-based architecture above that is, sorry to say, near insane.
Please, enlighten yourself and come to the real ASP.NET MVC world... :-)
PS: some people claim of having success implementing a MVP (Model-View-Presenter) architecture above ASP.NET WebForms. Shame on them (but you can try if you really want to)!
As others have posted there is a lot of information out there on MVC, so I'll answer your question...
If we have ABC.ASPX and ABC.CS files,
what is view? is it only ABC.ASPX
file? or combination of .ASPX + .CS
file?
It is both...however the .cs file is referenced as code behind but both make up the view.
do we consider ABC.CS file as
controller? If no, will it be a
seperate class for controller?
No, a separate class would be the controller.
Does database connection and data
retreival go into Model or a seperate
class which will be called by Model?
You could go either way. you could place this logic in the model, however you could also functionalize it out into services, which can then be called as needed by the model. IMHO the second route is the way to go, as I don't want to make my model dependent on external entities and it also makes testing the model easier, as you can separate out the services testing from the model testing.
Diagram can be seen here, which has some great imagery as reference points.
I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.
Are there any best practices that cover the places that ASP.NET MVC models should be defined?
A new ASP.NET MVC project has a nice neat Models folder for them to go in, but in a production environment they can come from other places:
Third party class libraries
WCF services
Is it acceptable for a strongly-typed view to use a class defined in such a location?
In just about every project I have worked on the models of ASP.NET MVC are more View Models than models in the traditional sense of the word. I have yet to have a project where I can use the same Model that I use in my data access for my View Model. There is just too much other information that needs to be displayed on most pages. So for that reason I will either store my models in the models folder or store them in a separate library with all of my other MVC specific classes.
I don't know what you exactly mean by putting models in WCF services. If you mean using WCF services that expose the model object you need, that would work.
Regarding separate class libraries to hold your models, views and controllers, I think that's a pretty common approach and works pretty well. In fact, I believe this is really a requirement when the size and complexity of your application grows. It's a kind of physical separation of the distinct logical components in an MVC app.
One issue that I've found is that, unless the model is defined in the web project, VisualStudio seems unable to find it when using a strongly-typed view specified in markup. My models are usually defined in a separate project and I've found that to use strongly-typed views, I need to create a codebehind so that I have a class that derives from a strongly-typed ViewPage. Then I change the markup and associate it with this class.
You need to import the namespace to the view page. This does not require a codebehind page.
Use the directive
<%# import namespace='your.namespace.here' %>
immediately after the <# Page..... directive
Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.