ASP.NET MVC 2: View Subfolders? - asp.net-mvc-2

It seems to me that as I'm working with View and Controllers, that Controllers only handle the first level of their respective folder.
/Controllers/MembersController
/Views/Members/
How is the Controller supposed to handle sub-folders?
/Views/Members/Business

The Controller isn't. If you want a page at the url /Views/Members/Business/ThePage, you'll solve that with a route definition in your global.asax.cs. If you need to put views in subfolders for organization, you should consider splitting up your controllers.
Update in response to your comment.
In short: yes, the routing definitions are responsible for choosing what controller should handle your request.
It seems that a slightly more detailed walkthrough of how the MVC framework was designed to be used might be in place. I'll keep this really basic, and skip all the stuff about the framework's internal workings. (That will make some advanced readers think I'm saying stuff that's flat out wrong. Please bear with me - I'm just being intentionally sloppy...) Here goes...
When a request is submitted from a browser to your web server, the MVC framework goes to the route definitions to see where the request should be sent. It looks through them in the order you define them, top first, so if there are several matches only the first one will be relevant. (Therefore, you want to keep your very general routes, like the default one, at the bottom.)
When the framework has decided that a route is a match, it looks up what controller and action the url should be routed to. It fills in all action parameters with data from the url, and calls the action method.
The action method on the controller is now responsible for being "the spider in the center of the web", that instruments everything that needs to be done to serve the response. This might include querying your model for data, calling various library methods for calculations or almost anything else. The final step of the controller method is determining what response should be returned - in most basic cases, the response should be a view, and the code for returning it is return View();.
The view (or whatever other result you're returning) possibly gets some data from the controller, and is then responsible for rendering this data correctly. When the view has done its job, the framework serves it back to the client.
As you can see, the decision on what controller action should be called is much earlier (step 1 and 2) than the decision on what the return result should be (end of step 3), and the two of them aren't even necessarily related to each other.
To reflect this in your application, you want to have a folder and file structure for controllers and views that corresponds to the available controllers and their action methods (at least those of them that can return a ViewResult), and a route collection that reflects what urls you want your user to use to get to these controller actions. By defining more routes than the default one, you can get quite a variety of url structures, without changing your controller/action method/view structure at all.
If all of this still seems like a labyrinth of decisions, it might be appropriate to go to http://www.asp.net/mvc/ and watch some of the learning videos or read some tutorials. There are some really good both videos and texts there about how the framework works, and how it's intended to be used.

In your controller action, you can return a view from any folder you want like this:
return View("/Views/Members/Business/Index.aspx", model);

If anyone is still interested in a solution, MVC has a thing called "Areas" that allow you to define subfolders.
http://msdn.microsoft.com/en-us/library/ee461420%28v=VS.100%29.aspx

Related

Restful WebAPI VS Regular Controllers

I'm doing some R&D on what seems like a very confusing topic, I've also read quite a few of the other SO questions, but I feel my question might be unique enough to warrant me asking. We've never developed an app using pure WebAPI.
We're trying to write a SPA style app, where the back end is fully decoupled from the front end code
Assuming our service does not know anything about who is accessing/consuming it:
WebAPI seems like the logical route to serve data, as opposed to using the standard MVC controllers, and serving our data via an action result and converting it to JSON. This to me at least seems like an MC design... which seems odd, and not what MVC was meant for.
(look mom... no view)
What would be considered normal convention in terms of performing action(y) calls?
My sense is that my understanding of WebAPI is incorrect.
The way I perceive WebAPI, is that its meant to be used in a CRUD sense, but what if I want to do something like: "InitialiseMonthEndPayment".... Would I need to create a WebAPI controller, called InitialiseMonthEndPaymentController, and then perform a POST... Seems a bit weird, as opposed to a MVC controller where i can just add a new action on the MonthEnd controller called InitialisePayment.
Or does this require a mindset shift in terms of design?
Any further links on this topic will be really useful, as my fear is we implement something that might be weird an could turn into a coding/maintenance concern later on?
If you are planning to make your services RESTful, the controller should represent a resource. In your example, the resource is Payment, so the controller would be called PaymentController.
You can have multiple POST methods in the same controller. In your scenario, I would call the action method PostMonthlyPayment or something similar. The URL (routing) would look like http://server.com/api/payment/monthly and the body (assuming JSON) would be something like:
{
user: user#internet.com,
month: 10,
year: 2013,
// any additional data
}
If the payment goes through, a good practice is to return HTTP error code 201 and the Location HTTP Header containing the URL to the payment GET method. If any data in the body is wrong, return a error code 400. If a payment had already been made by the user, conflict code 409 can work.
For SPA you will definitely need REST Web Sevice. My suggestion is to try servicestack instead WebApi

How many controllers to make in a framework generally?

I was wondering if there are any guidelines for the number of controllers to make in any web based frameworks. I know it depends on the requirement. But still if you would consider a basic application containing signup, login, user authentication, Sending emails, User Profile Edit etc..how do you decide about the controllers?
And if there are many common functions would you make a different controllers to hold them all? Some frameworks like Zend recommend to create helper files for that! Do you create category of helper files for different functions?
Looking at routing we have some sort of a guideline as to how many controllers and even actions we will have in Zend Framework. Although we have to keep in mind that we can do quite a few things to change this in one way (getting less) or another (have even more).
The basic and general rule in ZF for routing is to have a link path matching up with controllers and actions.
www.yourdomain.com/controller/action
Routing will dispatch to the corresponding controller and with it to the named action. When we follow this basic rule we will end up with a number of controllers that matches our number of paths we like to see.
You can basically create a root path for every piece of functionality for you website and end up with as many controller (with one action) or even combine everything within one path and hence one controller but as many actions.
Ultimately you will and should combine common features of your website into one path and controller, e.g. combine everything related to user management (signup, profile edit) into a /user path and UserController.
As for your examples I think User authentication is something that will not have its own controller but happen inside the Login controller or models used by that controller.
UPDATE
Controllers and their actions interpret requests and should only delegate to other methods. It may be beneficial to keep these methods in their own classes. How you structure this methods and classes is up to you. The Zend way is to keep them in your own application library, e.g. sending emails should be held and performed by a separate class in your own application library (next to and maybe extending Zend classes).
If you have a contact page you could have a /contact link with a ContactController. The indexAction will delegate everything to present the form page. The form could have a /contact/submit link for the submit button and a corresponding submitAction will hook up your email library class and send out the email. The submitAction finally may call something like _redirect('/submit/thankyou') or even /submit/error. As you may guess by now there will be a thankyouAction responsible for presenting a Thank you page or a errorAction to let the user know there was an error.

GWT MVP introduction questions

I have read a lot of gwt-mvp questions that are asked here, but since i'm totally new to this design pattern I would like to ask some questions:
[1] The Activity-Place pattern is a different pattern than mvp?
[2] In the MVP pattern presenters contain the logic. Now the logic of the widgets/controls is defined in the Activities?
[3] The CustomPlace classes are fixed (as the Eclipse plugin constructs them) or can i put data/methods and what kind?
[4] What is the use of the Presenter interface inside a CustomView? What data/methods would make sense to add into it?
[5] I want to build an application that will use many data structures that will be saved into a database. I have read some other posts here and I will make the Model part of MVP live inside each Activity. So i think to create each time the data structures of each activity at start and load its values (if necessary from db) and will update the database after the user goes to another view. What do you think about this approach?
Let's start by debunking one myth: Activities/Places have nothing to do with MVP. Places is about navigation, Activities are about "componentizing" the UI wrt Places. On the other hand, MVP is a design pattern, it's about how to organize your code.
Many people are using their activities as their MVP-presenters, but it's not enforced. The GWT team is trying a new approach where the activity is distinct from the presenter (work underway in the mobilewebapp sample if you want to follow what's going on there). You could also have your activity being your view and making use of an "internal" presenter (similar to how Cell widgets work)
A Place is more or less a URL. You can put whatever you want in it. I'd suggest making places immutable though: build a Place, goTo it, make use of its properties to build your UI.
That's about MVP then. This is only needed to decouple your view and presenter, mostly to make mocking in unit tests easier (this is particularly of the view interface though, not much for the presenter one, unless writing a test harness for you views). In some cases, you might also want to use the same view with distinct presenters; they'll all implement the same interface so the view can talk back to them.
How about the closing of the window/tab? I'd rather use a periodic auto-save, or an explicit save button; and implement mayStop so it prompts the user when there are unsaved changes (similar to how most desktop office apps work —e.g. MS Word or LibreOffice—, and GMail if you try to navigate away before your mail draft is auto-saved)
The Activity-Place is an implementation of the pattern. Google introduced gwt-mvp pattern at Google IO, but only provided it's implementation as part of GWT about a year later.
Yes Activities contain business logic. No, widgets/controls usually do not contain any logic, they just fire events based on user action. The logic that acts upon those events is written by user and resides elsewhere.
I don't use Eclipse, so wouldn't know about Places generated by it. Normally custom Places can contain custom fields and methods. For example they can contain custom place token arguments, i.e. if place token is "#place:id1", than your custom Place could contain field holding this argument.
When View needs to call/access Activity, it does so via Presenter, which Activity implements. For example when user enters all data in a for and presses submit, then you could have a method in Presenter named submit(formData).
Preparing/loading data in activity.start(..) is a normal way of doing things. If particular activity is used a lot, then you might consider caching the data if appropriate.

asp.net mvc2: Why to minimize the code in controllers?

I heard a bit about we should keep the code in controllers as less as possible. So where do we put those code?
This will depend on what code you are talking about. For example if you are talking about validation, this should go into the model, if you are talking about data access this should also go into a repository or the model (personally I prefer repository), if you are talking about a business logic this should go into a service, so that all that's left into the controller is to call this thing and pass the result to the view.
I would recommend you watching this video presentation about how to put your controllers on a diet from Jimmy Bogard.
Do you know thin and skinny controller? So my answer is if you put many line of codes in controller, your code will be messy and hard to unit testing. Really the controller only executing the actions related with current HttpContext, so if you have business logic, data access, encryption,... you must separation of concern. The reason you don't put business logic at here is business belong to domain. So delegate to Domain for processing. Controller must be consider all actions related to HttpContext (Session, ViewData, TempData, User in current thread, Global and Local Resources,... ) and delegated all other actions to other component. Rule of thumb is fat model and thin controller for cook delicious cake(phpcake).
Some links you can reference for skinny and fat Controller at here and here.

Yet Another MVVM question... Is my understanding correct?

Sorry if this is a duplicate, It's not so much 'What is MVVM' though, but rather, 'Is this MVVM', I've read quite a bit, and think I've got a basic understanding of what it is, I've got my own 'one-liner', as such, on how I interpret it, but want to make sure it's correct before I firmly ingrain it in my head,
Essentially; The Model is pure data - no methods, there is one ViewModel per Model, it holds a reference to the Model - it performs all changes to the Models data and finally the View will hold one (or more) ViewModel reference(s) and format & display the data provided by the ViewModel.
(Not after links to tutorials, blogs etc, just a yes, or no with tweaks will be fine, as I'll have to re-read everything again anyway if not :) )
Not completely - at least, not as I would completely define it.
The Model does not have to be pure data. The model is the portion of your application that is completely domain specific, and has no "presentation related" information.
This will typically include all of the domain specific data, but also potentially methods that are pure business logic, and data access, etc. Anything specific to the business logic and processes, and not part of the "display", is part of the model.
Also, although "one ViewModel per Model" is the most common form of working, there are times when you may expose a "model" class through multiple ViewModels. This can be useful, for example, if you are trying to expose only part of a model to your designer, as it allows you to make a smaller ViewModel class. The ViewModel adapts the model for work with the View - if the entire Model is not required, this adapter can be made smaller (and more easily testable, maintainable, etc) by only working with the portion required.
Personally, I prefer to think in terms of "one ViewModel per View", as the ViewModel can adapt one or more models in order to work appropriately with a given View, but even then, sometimes it's helpful to swap out a ViewModel within the same View in order to change content.
Close, but not quite. Here are some points that are are different than yours:
Models can have methods on them. They are not just data. They might have methods like "retrieve", "store", etc. Business logic code. View agnostic.
There is no restriction to how many ViewModels hold a reference to the Model. ViewModels encapsulate view-level behavior, so you may have many different sets of behavior for the same model. For example, one ViewModel might be a read-only transformation of a model item. Another might provide read/write form validation on the same model item.
There can be more than one ViewModel per view, based on the behavior you want. For example, you might include "premium content" behavior with one ViewModel and "free content" behavior with another ViewModel but maintain the same view.
Essentially, yes. Practically, not really. Best practice is always to reduce dependencies and split up your responsibilities among classes on a 1:1 basis, but you'll find IRL situations where it isn't as easy to be a MVC purist.
I think the best attitude is to do your best, then document the rest. Don't sweat purity too much.
There is a lot of great information here, and I think that most of these answers are right. I don't think there is any 1 specific definition, nor is there 1 specific authority on this matter. Even microsoft does not really have clear definition on this.
The one item I would add which is not in the name of MVVM, but is common to all implementations of MVVM that I am familiar with. This is a Messaging or Notification system, which seems to always be linked as a platform for the ViewModel. Messaging just notifies the View Models when things change which may affect others. A good implementation of this in mind allows View Models and Views to both be agnostic about things they do not directly bind to by using generic notification messages.
The benefit of the entire pattern in my opinion is to make you application with modular, swappable parts with as little type-dependency as possible.
This is a real missing part in my mind, as it provides the same benefits / functions that you gain from separate controller logic in the MVC pattern.
That is pretty close. Except it is not correct to say that the Model is only pure data. It can and should contain methods for performing the various use cases against it.
Your understanding is wrong.
You can have several Models and all of them could have their own Views and then be a part of a single ViewModel.
Example:
You have the Models: Product, Customer
Each of them have their own View represented as a Custom Control
And you have a ViewModel which combines all your models and finally on the window of your app you combine all together your Views which talk to your Models via your ViewModel
Think of it like this. The Model is your system, the meat and veg of what the system does. The only considerations it has is how to do it's job, not how it is going to be used. It exposes events, attributes and methods defined at the system level, but it has no concept of what will be pressing it's buttons (or if it even has buttons!). It does not try to format data to a more user friendly format, it formats its data in a model friendly way.
The view model is the UX (user experience). It defines how you are going to use the system. It defines (through public commands and attributes) user orientated access into the system. It is the bridge that the user will use to enter the system. It binds onto the events of the model, and through it's commands, it will provide access into the models functionality.
It should handle validation, (is that age a sensible age?) retrieve data, converting and caching of records whilst they are being displayed. So, for example, you're looking at a patient record, the viewmodel gets the data from the model, and caches it internally, then publishes this to the view. What happens if the model announces an update to that data? Throw the cached data away? what if you've edited it? This is all up to you, and this behavior should be defined in the view model.
The view model is a "contract" of what functionality and data is exposed to the user (through the view). The view model has no concept of HOW it is going to be displayed or interacted with. Commands should be named at a functional level, such as RefreshList, NOT MouseClickHandler.
Finally, the View. This is simply a visible representation of what is in the view model. Buttons and menus etc bind onto commands. Fields bind onto attributes and will update automatically through the magic of binding.
If you ever see yourself doing : "text1.text = value" you're doing it wrong. If you ever find yourself writing a command handler that says "my.ViewModel.SomeCommand" you're doing it wrong.