How to get access to Model in regular Spring Bean - spring-mvc

I'm having some problems with accessing org.springframework.ui.Model in a bean not annotated by #Controller Using #AutoWired fails in this bean and it isn't created. Similarly, if I try to make Model a parameter to a method in this bean it is not injected and the method call fails silently.
The reason for the need is to supply dynamic data to some views in my site such as allowed links for a user, or custom welcome messages. Theses elements may not be on every page. I've seen some tempting frameworks like Tiles. View templates were working, but needed model element on partial views was not being populated.
I've seen similar posts such as Add attributes to the model of all controllers in Spring 3 but this would add to all views which is not correct in this case. Any help or pointing in the right direction would be appreciated.

Related

Custom ErrorMessage for model validation attributes

I am new to MVC, so please bear with me.
We have a large WebForms website, where content is managed by a
custom CMS. I have added DataAnnotation attributes to my model
properties. The attributes have an ErrorMessage property, but this
must be a compile-time constant.
I would like to get error message texts at runtime from out custom
CMS. We already do this in our WebForms pages, so the infrustructure
is in place i.e. manager classes with aproprate methods for retrieving
the correct texts by key.
My question is where do I hook in at runtime in order to populate the
texts from the CMS to be displayed when validation error occur
client-side or server-side?
One way I guess would be to create your own DataAnnotationsModelMetadataProvider. Derive from this class and override the CreateMetadata method. Don't forget to register your custom MetaDataProvider with the ModelMetadataProviders when your WebApp initializes.

Where to place common business logic for all pages in symfony2

I am now working on my first symfony2 project. I have created a service, and I need to call it for every controllers to generate a html which is necessary throughout the all pages in my website.
So I created a BaseController class which extends Symfony\Bundle\FrameworkBundle\Controller\Controller class and tried to place the code in this BaseController class. Now whenever I call from the constructor:
$my_service = $this->get('my_service');
or
$my_service = $this->container->get('my_service');
I got error:
Call to a member function get() on a non-object.
The container object has not been initialized. What is the solution to this problem? How DRY method is followed in symfony2, if I want to place left panel or header in all pages which contains dynamic data?
Thanks in advance.
You shouldn't use the constructor in your controller class, especially when you inherit from Symfony Controller: that way you get the container after the object instantiation (the DIC will call the setContainer method inherited from Symfony's Controller).
In general, for your first experiments, use the services in the action methods; if there is some cross-cutting logic that you need to execute in every request you could consider registering some event listeners (see the "Internals" docs in the Symfony website).
When you get more confidence with the framework you can start thinking about not inheriting Symfony's Controller, registering your controller classes in the DIC and injecting the services that you need manually (eventually implementing some logic in the constructor).
I know this is not the answer you desire, but if you need some html on all pages, I think using a service the way you do is the wrong way.
I guess you know about twig and the possibility to use a layout to place common code. But you can also embed a controller:
{% render "AcmeArticleBundle:Article:recentArticles" %}
Within the recentArticlesAction, you can place your specific code and return a template. By this, you can get custom html into each of your templates! See the symfony docs for more: http://symfony.com/doc/current/book/templating.html#embedding-controllers
Business logic is all the custom code you write for your app that's not specific to the framework (e.g. routing and controllers). Domain classes, Doctrine entities and regular PHP classes that are used as services are good examples of business logic. Ref

Where to intercept resolution of controller/view in ASP.Net MVC for customizations?

I am trying to figure out where the appropriate place is to intercept the resolution of what view + controller is being called in ASP.Net MVC 2. I have a situation where I have a controller and a corresponding set of views. I also have the possibility of a customized version of both the controller and N of the views sitting in the project (or we may use something like Portable Views from the MvcContrib project). If the customized version of the controller or view(s) exists at run time, and the user satisfies certain criteria, I need to call the customized controller and use the appropriate customized view. At design/compile time we don't know what customizations may be in place.
My first run at this was by using a custom controller factory that returns a custom controller if it exists. However, this controller is "wired up" to the standard view, and I cannot figure out how to return the customized view if it also exists.
To complicate matters, there may be no customized controller but customized views, and visa-versa.
Sounds like you're on the right track. You've got custom controller selection logic in place, but you need to also have custom View selection logic.
You can override and extend the default ViewEngine to plug into your app that uses your own logic to look for the view locations. Here's a good walkthrough of a simple ViewEngine that does exactly that.

ASP.NET MVC - How to achieve reusable user controls and maintain DRY?

First post so please be gentle :)
When creating user controls in ASP.NET MVC, what is the best way to structure the code so that the controllers that invoke views that use the user controls do not all have to know so much about the controls? I would like to know a good way to maintain DRY while using user controls in ASP.NET MVC.
Please note, this question only pertain to user controls that require special handling and logic on a postback. I have no problem creating nice DRY code for user controls that are either view only (using RenderPartial) or that require some pre-processing to create the appropriate ViewModel (using RenderAction).
Also, this question pertains only to achieving reusable controls within an application. I am not worried about reusability between applications at this point.
To give a specific example, let's say I would like to create a 'Quick Add' user control which contains three entry fields, First Name, Last Name and Company Name and a submit button. When the QuickAdd functionality is used, the following steps should be performed independent of what page the control is on:
Validate that the fields were not empty, if they are, show an indicator.
Perform a lookup to a repository to see if the Company already exists, if not; create it.
Create a new contact associated to either the existing company or the newly created company
Re-render the existing page. If no validation errors, the user would see the exact same page again, otherwise the same page with validation errors.
My main problem with achieving DRY has to do with all the controllers that invoke views that contain the partial view end up having to have an Action Method to process the form submission from the Quick Add. Even if I break out the logic for processing the information into a separate controller and invoke that method from each of the other controllers it seems like a burden that each and every controller that invoke views that have reusable controls have to have that knowledge.
The other option I looked at was to have the reusable control always submit to a specific action method / controller but then there is no way for that controller to know how to re-populate the model appropriately for the specific controller that invoked the view that contained the reusable control (in step 4).
I am aware that there is talk of subcontrollers in MVC 2 (from this question ASP.NET MVC - Contained User Controls) but since it is not there yet, what is the best way to structure the code to achieve maximum reusability while maintaining DRY?
Is there an alternative to having to have all the controllers that invoke views that use a reusable control (with the characteristics of the one described above), having to have an Action Method to process the information from the control?
At the end of your post, you ask "Is there an alternative to having to have all the controllers... having to have an Action Method to process the information from the control"
The answer for that question is to write a custom model binder. Your custom model binder can be responsible for the populating the values from the incoming form control(s) into model or properties used by all of the controllers. Normally, you want to separate the validation from the model binding, but there is no reason that you couldn't combine them as well.
I highly recommend 6 Tips for ASP.NET MVC Model Binding for a deeper discussion of the topic along with some good references.
I'm not sure why you say the Quick Add form has to have an action method in each controller that uses it; if you wrap the Quick add functionality in a Html.BeginForm(); Html.EndForm() combo, you can have the beginform method specify the name of the action and controller, so you only need one controller.
I understand where you are coming from; it's something I have been thinking about to. While I don't know all the answers, I have some ideas for you to consider. Every controller action method is invoked via a ControllerActionInvoker class, which you can customize. This class handles invoking all of the action methods, so here you could embed certain aspects of reusable code across all or certain action methods.
Look into filters too, as there are a variety of filters that you can use or customize that fire for action methods that implement it. This way, code can run before and after the action method execution and result execution.
For validation, there is already validation components built in that will prevent page submission... you could also consider XVAL which has some other nice features. The Unity framework is an IOC container framework, which dynamic injection keeps things loosely coupled and DRY, as you can inject all kinds of references.
Also, you mentioned subcontrollers; the MVC preview has additional features you may be interested in... for instance, it has a RenderAction method that can render an action method within another action's view.
Hopefully that helps... so what am I missing?
Have a look at RenderAction and RenderPartial. Those are the canonical ways to arbitrarily inject a common control into a view.
Use RenderPartial when you want to include the data as part of your ViewData infrastructure.
Use RenderAction when you want the data to be separate from the ViewData infrastructure. The data will come from the controller method you specify in RenderAction.
Check out the NerdDinner tutorials, if you haven't done so already.

Using a Base Controller for obtaining Common ViewData

I am working on an ASP.NET MVC application that contains a header and menu on each page. The menu and header are dynamic. In other words, the menu items and header information are determined at runtime.
My initial thought is to build a base Controller from which all other controllers derive. In the base controller, I will obtain the menu and header data and insert the required information into the ViewData. Finally, I will use a ViewUserControl to display the header and menu through a master page template.
So, I'm trying to determine the best practice for building such functionality. Also, if this is the recommended approach, which method should I override (I'm guessing Execute) when obtaining the data for insertion into the ViewData.
I'm sure this is a common scenario, so any advice/best-practices would be appreciated! Thanks in advance!
EDIT:
I did find the following resources after posting this (of course), but any additional anecdotes would be awesome!
http://www.singingeels.com/Blogs/Nullable/2008/08/14/How_to_Handle_Side_Content_in_ASPNET_MVC.aspx
How do you use usercontrols in asp.net mvc that display an "island" of data?
Depends on where your information is coming from. We have standard view data that we use to generate some of the information we have on screen that we create in just this fashion. It works well and is easily maintained. We override the View method to implement strongly typed view names and use this information to retrieve some of the data that the master page requires as well.
You could write a helper extension to render the header/menu
That way you could have it show in different places in the view should you need to, but only one place for maintenance.
public static HtmlString MainMenu(this HtmlHelper helper)
Use a base controller class to implement generell filter methods. The controller class implements some filter interfaces IActionFilter, IAuthorizationFilter, IExceptionFilter and IResultFilter which are usefull to implement some common behavior for all controllers.
If the menu data is the same on all pages but different for each unique user.
Generate the menudata in an OnAuthorization or Initialize method of your controller base class. First will be called on authorization. Initialize will be called before every action method. You have access to ViewData Context. Generate the menudata there.
Put the view content for menu and header into the master page and access generated ViewData there.
I tackled a similar design challenge a couple months ago - implementing a breadcrumb feature that changes as user navigates from page to page.
I overrided the OnActionExecuting method to gather the breadcrumbs and store them in ViewData (I use the name of the action as the breadCrumb of the view). Then I updated the Master page to include a user control that takes the ViewData and renders the breadcrumbs.
One thing to be aware is that if you were using the default ASP.NET MVC error handling attribute [HandleError] and your error page is using the same Master page that attempts to read the ViewData, you will soon find out that you can't access ViewData from your error page and it will raise an exception. Depending on whether you need the ViewData for failure scenarios, the viable solution is to use a separate Master page or do this: How do I pass ViewData to a HandleError View?
I'll answer your question with another question. Will the base controller have to determine what type it really is in order to generate the proper menu data? If so, then you're defeating the purpose of polymorphism and the code to generate the data should go in each controller, perhaps in OnActionExecuting if the menu is the same for all actions. Pushing it back down into a parent class seems likely to end up with some switch statement in the parent class doing what each derived controller really ought to take care of.

Resources