Problem
While developing struts2 application I was asked to implement two pages: the one listing current user's books and the other listing current user's CDs. So I decided to implement two struts2 actions: ListBooks and ListCDs, both of them having standard dispatch result type, pointing to corresponding JSP pages.
Later the client changed his mind and decided that both lists of books and CDs should reside on the same page. So how can I reuse my actions so that I wouldn't need to rewrite any classes.
My attempt
First approach was to use action chaining. So that both actions can contribute their properties to value stack. But then there is a problem: we establish some unnatural order for actions. If I chain ListBooks to ListCDs then invoking ListCDs on its own causes some erroneous behavior - as it will result in a page where both books and CDs should be listed.
Another way was to use action tags. But I don't like it either as it forces separation of my page into multiple JSP parts and generally feels like doing things not in struts2 style.
Questions
So how do I combine my actions to form single page in a "clean way"? The problem seems to be so simple.
Another question spawned by this problem is about struts2 design - do struts2 actions take too much responsibility? Apart from being "single units of work" they are also coupled to presentation level. Everytime I change the structure of my pages I have to think about redesigning my actions. Am I missing something or struts2 really has this type of design weakness?
Struts 2 actions only take too much responsibility if they're designed that way--they should act as a thin bridge between the web and business layers.
Each of the earlier actions should have just had a service to retrieve the items in question. The new action would have both services, and expose the results of the user's books and CDs to the view layer.
Of course they're coupled to the presentation level--they are what determines what's available to the view. In any action-based framework this is the case, whether it's the action itself, the model in a ModelDriven action, a Spring MVC controller returning a view, a Struts 1 action form, request attributes, etc.
The amount of work necessary to support the type of change you describe is almost nothing: move the service from one action to another, and either expose the additional results directly, or add them to the exposed model.
Related
I have followed this nice tutorial which explains how you can take even more advantage of using Umbraco as a content delivery system. Tutorial MVC Umbraco => Your model and views should not depend on specific Umbraco implementations which is a huge advantage for real front-end developers.
The controller inherited from Umbraco.Web.Mvc.RenderMvcController in order to access the data from the CMS.
Now my problem is that we can't use #HTML.actionlink for navigation, it seems that this is only supported in SurfaceController.
Now my question is how would we implement navigation inside Umbraco.Web.Mvc.RenderMvcController? Can we still use the native #HTML.actionlink tag?
No you can't. Simply because all requests pass through a single action. In order to retrieve a path to a CMS-managed page, you need to use the node/content traversal the #Model provides. See here for more details on this.
Edit
To clarify, the author of the article is suggesting that the Umbraco implementation should be more in line with a traditional MVC implementation with little or no logic in the views. Therefore, any querying of node data should happen prior to the view (e.g. in the Mappers). So this is where you would have to retrieve the links.
Umbraco's default MVC implementation forces all requests to go via a single action on a single controller. The author's implementation allows the requests to be shared across one controller per document type - which is better IMO. But it still means that things like Html.ActionLink are redundant in the views since there isn't an action per page.
Further edit
If you wanted to build a navigation list with a combination of Umbraco-managed pages and non-Umbraco pages, regardless of the implementation, I would:
Create a child action and view for the navigation in a separate NavigationController that inherits from the SurfaceController
Use the this.CurrentPage property of the inherited SurfaceController to traverse the Umbraco content cache to retrieve the relevant Umbraco-managed pages. You can then use the Url property of each page result to get its path, and the Name property to get the page title
Use this.Url.Action("action", "controller") to retrieve the paths to specific non-Umbraco actions. Alternatively, if the pages are database-managed, use you data layer (e.g. EF, NHibernate, PetaPoco) at this point
Combine these in a Dictionary to make the list you require where the Key is the path and the Value is the page title
Pass this down to the view as the view model.
Of course there any many more things to consider like caching, but in a nutshell, that's a fairly basic implementation.
We're going to be building an application using MVC 4. A key requirement is view-level auditing. In other words, we must be able to show who accessed a view/screen (person details, for example), the parameters to create the view and when the view was accessed. This is a new application so we can do almost whatever needs to be done to address this requirement.
The database will be SQL Server 2008. Data access will include EF 4.x, possibly 5.x but not a sure thing.
My question, how do I get started designing this feature? Are there any sample applications out there?
Don't mind auditing at view level. I think it is better to audit actions. You can do this using global action filters (for example here).
EF does not work very well with Views. You might be better of with either a straight ADO.NET persistence layer that you hand code, or Linq2Sql is a little better about using views (you still have to hook them up manually though). nHibernate would probably be the best ORM to use.
EDIT:
#user1469655 - You have a very fundamental misunderstanding of how MVC works. The "view" is not a page. It's a template. The "page" as you might consider it (ie accessing a specific url) is really a combination of two different things, a route and an action. An action can cause a specific template (view) to render, but there is not necessarily a 1:1 correlation between action and view.
An "action" is a method of a controller. This is mapped to a URL by a route. Typically (but not necessarily), this means something like this:
http://www.my.site/controller/action
When a user visits this URL, it causes the action method to be called, and potentially for a view to be rendered. Different actions can render the same view, because this is nothing more than an html template that can be rendered at will by any action method.
So what you want to do depends on what you are actually logging. It makes no sense whatsoever to log access to the view, because that doesn't actually mean anything. What you want to do is log access through the action, or possibly even log it through the route.
The simplest way to do this is to use a global action filter that is called before every action, in that filter you can log the information you need to (user id, date, time, action, referrer, whatever).. and it gets called for every action. It will not, however, get called for ignored routes (such as for content like javascript, images, css, files downloaded directly, etc..). If you need to log those, then you will need to control access to them via an action.
There's a good tutorial on Action Filters here
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs
I am interested in general approach for building interactive GUI using MVC3.
The idea is to build set of different components that can be integrated (plugged in) into various scenarios.
Each Component MUST have it's own model definition, controller and views.
Component encapsulates not just the view but also behavior through it's controller.
All internal implementation details, model, behavior, etc... must reside inside component,
so that component becomes independent, modular - black box.
This allows component to be changed without breaking anything in context in which component is used.
Context in which component runs must not make any assumptions about internal details of component implementation.
On the other side the component does not make any assumptions about context in which it will be used.
Finally, the component must provide mechanism to "communicate" or "interact" with outside world. Beside internals, component must provide some kind of "external" interface (like parameters, data, functions, events whatever...) which would allow component to be integrated into execution context.
The Context (or scenario) is part which contains components.
Now, the basic challenge for the context is to manage interaction between components.
Real-world Categories component example:
Component displays list of categories and allows user to perform various actions such as sorting, paging and record selection.
Internally, it has it's own model which stores relevant information like current page, sort, selection, etc...
Internally, it implements all required actions (for basic render, for user actions response, etc...) in it's own controller.
Internally, it handles model state persistence in the view and model state restore in it's own controller.
Real-world Products component example:
Component displays list of products and allows user to perform various actions such as sorting, paging and record selection.
Internally, it has it's own model which stores relevant information like current page, sort, selection, etc...
Internally, it implements all required actions (for basic render, for user actions response, etc...) in it's own controller.
Internally, it handles model state persistence in the view and model state restore in it's own controller.
Real-world Dashboard page (context, scenario) example:
Page displays both Categories and Products components.
Products component displays all products for the currently selected category and thus must provide external interface (parameter or something) to receive selected category identifier from the context.
Categories component must provide some kind of external interface so that context can act when selected category changes and provide selected category identifier for the products component.
Technically, communication approach for page updates would mostly go through AJAX but if this is possible without AJAX, it would be even better.
In the case of AJAX, I would like solution which uses server side controller(s) which decides and renders what should be updated on the client (JSON or something).
I would not like solution in the client script (client side "like" controller) which decides what actions to call and what parts of page to update - this as said in previous paragraph must be decided by controller(s) on the server.
Important: It is not necessarily for the components to work when directly called via some route.
How would you generally implement described system?
I think you need to investigate real projects and see, what approach do you need to use. Try following project and u can find many best practices:
Here u can find implementing of security measures, services, auth and many many useful.
Kigg
http://www.nopcommerce.com/downloads.aspx
http://orchard.codeplex.com/
It's hard to say for me how it's should be implemented. Better to code it. But using of Dependecy Injectction of Views, Controllers, Services, and Repositories are must in your case.
Each controller handles a whole user-machine pattern. That is, roughly, each controller is responsible for orchestrating the user-machine interaction for a user-case(the user-machine patterns that are the result of the analysys phase).
Now if you put "standard behaviours" in controllers who will coordinate the user-machine interaction pattern?
This way you will have "components" without something that coordinate their execution.
In web forms you have pages that coordinates the execution of components put in them...but in Mvc thi coordination role is played by the Controllers themselves.
You can do black-boxes composed of Controllers and Views just if each of them is responsible of a whole user-machine interaction pattern. That is a "Big Components" not a small building blocks, as its is the case when you implement a CMS.
The Orchard CMS use a similar approach. However what you call components are actually pre-defined blocks that play the role of whole sections of the websites being built by the user.
It seems to me that you are trying to achieve something which may not be out-of-the-box compatible with the philosophy of web MVC (other implementations of MVC might support it).
However, if you wanted to go to the trouble of writing a framework on top of ASP MVC, I am sure you could achieve what you want. For example, by using Areas, you could achieve a form of encapsulation of your controllers, view models, and views.
To compose different areas for the same master view, you could write the equivalent of a front controller with its own view that took in a view model - that view model would be primed by the front controller to render actions from the different areas.
You might achieve more mileage by using a client framework such as Backbone.js on top of ASP MVC.
I am a bit new to ASP.NET MVC and I have a bit of an ordeal. I am developing a website with several roles in it and of course the logic and gui that the user gets depends on the role (duh).
There are 10 separate roles in this application. They do share most of the same functionality but some screens will be different depending on which roles they are in.
Heres my question. All examples and tutorials I've read on the internet and the Apress book that I have been reading show an example how to implement roles with one role (Admin) in which the common way is to provide an Admin Controller (or even Admin area) for the authorized section of the site. However, what if there are 10 roles? Do I really need to code up 10 separate controllers?
Let me help the question by giving detail what is being developed. There will be a menu and the menu items will be filtered by role of what views(or pages) they can and cannot get.
The from what they select, it will provide them a restricted view(or authorized page) which from within will provide a plethora of functionality limited to just that role.
I know there are several different ways to do this, I just want to know what is the recommended or "clean" way.
Have any of you been in this situation and if so, how did you organize the logic for multiple roles? Separate all roles to separate controllers? Have few controllers but just apply authorize filtering on the action methods? Apply the role filtering within the views or partial views and leave the controllers alone?
Unfortunately there are little resources for how to implement several roles out there, I just want to know how to do it the "correct" way in terms of separating the logic.
I would put the pieces of functionality into partial views. Have one controller per piece of website and load partial views based on the role and what should be exposed.
I would only stray from that if you have an excessive amount of differences, like an administrator would possible have. Then I typically make an area to encapsulate that functionality.
Regardless of the controller separation I would definitely use partial views to minimize duplication of similar code. You will reap the benefits when you need to maintain that code.
Use Authorize on the action methods and apply the roles allowed for the operation.
Depending on what's appropriate for the scenario, build a list of available actions from the controller and send that to the view as part of the view model. In some cases its more appropriate to send a simpler view model that tells the view whether each operation is allowed i.e. CanDelete, CanEdit, CanViewDetailedInfo etc.
I'd start with that, and depending on the actual complexity re-factor to any combination of:
An ActionFilter that populates the available actions / instead of explicitly doing it in the controller
Use reflector to look for the list of roles applied in authorize / so you only specify roles once
Your own html helpers that take authorization into account. So when you declare an action link, its only output when the action is supported.
I just finished Scott Gu's Nerd Diner tutorial. I found it very helpful because it not only taught the basics of ASP.Net MVC, but also how to use with Repositories, Validation, Unit testing, Ajax, etc.. Very thourough, but still manageable.
However, I am curious about his site structure:
Specifically, he used this view strucuture for every object:
/ModelObject/Edit/
/ModelObject/Create/
Then extracted the common elements between the two views and put them into a partial.
I understand the logic, but it seems like it would lead to "view explosion" if you have even a moderate number of tables in your database.
Scott's really good, so I am assuming his structure is right. But I would like to know why.
Thanks!
[Edit for clarification]
I realize that many times it is necessary for there to be multiple actions (and views) to handle differences in creates and edits. It is the case of the very simple edit and create, where the only difference between the two actions is in one case the model has an ID and needs to be updated, and in the other case the model does not, so it needs to be inserted.
In this case, is the violation of the "Dumb View" rule by using the same view to handle both cases going to cause major problems?
The view structure is based on the controllers, not the model directly. In the Mvc methodology, you should have a view for each action (each public method, essentially) in a controller. The controller actions don't have to match up directly to each table in database but there is likely some sort of direct relationship between the number of tables in the database and the number of controllers and views. Controllers are higher level
It is standard to have CRUD type actions on the controller, when they are applicable:
Index: list the items
Details: view a specific item
Edit: edit an item
Create: new item
Delete: delete an item
Each of these actions will require a view (and sometimes more than one).
So, yes, you can collect a large number of views if it is a large application. The way to minimize the code is:
Extract shared functionality to partial views, as to keep the action views as small and simple as possible
Keep the views and controllers simple so that they are easy to maintain
Use AJAX to implement more functionality in one view
It's important to point out that any large application is going to have lots of forms. Whether it's Mvc or Web Forms, if there is a lot of data to work with, there are going to be a lot of forms necessary to do it.
It is true that this can indeed lend itself to a lot of views. However, I've found that in my real life applications, I'll have a number of tables that I don't have a 1:1 correlation to CRUD operations. While I certainly have data that goes into those tables, I've found that most times a view presents data from at least two if not three or more tables. Just like every other application, you've got to know what you're after so that you can plan things out. Any large size application is going to require quite a bit of planning up front (which would include analyzing the number of views/controllers for MVC).
It's only the small apps that you can sling together based on you hunches and past experience.
if you have a background as asp.net webforms developer, your answer is natural.
There are several questions, it depends on the point of view. At first, with asp.net-mvc we do not have fully-equiped server controls making many things for us, without a real awareness what they do. Now you have to type more code and have eyes like a surgeon on html.This way I can find a reasonable question for "view explosion"
Other projects follow more or less that structure, see the project by Rob Conery:
Mvc Storefront
PS: "Skinny controllers, Fat Model and… Dumb view"
[Update response to clarification]
Mhh.. I think there's no violation of "dumb view". The important thing is that the all the views has nothing to do with the code in the business logic layer or in your model. You can a have a button "Save", it is the controller has to know which action must be executed, insert or update.
On more reflection, this is what I am thinking:
Combining the edit/create views would be easy on simple models because
- Same properties displayed
- Same validations
BUT doing this would force you to either
- handle both the update and insert in the same action
- use a control statement in the view to determine which view action is used to update
Both options seem ugly and unnecessary when it is so easy to use separate actions and separate views with common code extracted into a partial.