EzDevInfo.com

controller interview questions

Top controller frequently asked interview questions

Allow multiple roles to access controller action

Right now I decorate a method like this to allow "members" to access my controller action

[Authorize(Roles="members")]

How do I allow more than one role? For example the following does not work but it shows what I am trying to do (allow "members" and "admin" access):

[Authorize(Roles="members", "admin")] 

Source: (StackOverflow)

asp.net mvc3 return raw html to view

Are there other ways I can return raw html from controller? As opposed to just using viewbag. like below:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.HtmlOutput = "<HTML></HTML>";
        return View();
    }
}

@{
    ViewBag.Title = "Index";
}

@Html.Raw(ViewBag.HtmlOutput)

Source: (StackOverflow)

Advertisements

Angularjs: a Service that serves multiple $resource urls / data sources?

I have an Angular service/provider that serves json data to my controller which works great:

    angular.module('myApp.services', ['ngResource']).
      factory("statesProvider", function($resource){
      return $resource('../data/states.json', {}, {
        query: {method: 'GET', params: {}, isArray: false}
      });
    });

But I also need to serve json data to the same controller from another file counties.json.

Where can I find out how to I write a service that serves both files to my controller?


Source: (StackOverflow)

Can an ASP.NET MVC controller return an Image?

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requested:

www.mywebsite.com/resource/image/topbanner

The controller will look up topbanner.png and send that image directly back to the client.

I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.

Is this possible?


Source: (StackOverflow)

Downloading a file from spring controllers

I have a requirement where I need to download a PDF from the website, the PDF needs to be generated within the code, which I thought would be a combination of freemarker and a PDF generation framework like iText (any better way?). However my main problem is how do I allow the user to download a file through a Spring Controller?


Source: (StackOverflow)

How to create a simple 'Hello World' module in Magento?

How can the following be accomplish in Magento?

  • Display a "Hello World" message using a controller/view/model approach. So, if I went to http://example.com/myController it would show the string 'Hello World'. Being able to show this string within the template of my website (for example, the header, footer, etc.) will be a bonus.

  • How to add a method to this controller (or a new controller if necessary), which interacts with a model, and performs the query Select * FROM articles where id='10' and returns the row (containing the columns id, title, content) to the controller? And then use the controller to include a view, which would display this row. So going to http://example.com/myController/show_row (or something similar) would display the row within a view. (No need to be fancy, just a echo $row->id; or something similar would work.)

Any other information about Magento's code structure will also be very helpful.


Source: (StackOverflow)

How to create separate AngularJS controller files?

I have all of my AngularJS controllers in one file, controllers.js. This file is structured as follows:

angular.module('myApp.controllers', [])
  .controller('Ctrl1', ['$scope', '$http', function($scope, $http) {    
  }])
  .controller('Ctrl2', ['$scope', '$http', function($scope, $http) }
  }])

What I'd like to do is put Ctrl1 and Ctrl2 into separate files. I would then include both files in my index.html, but how should that be structured? I tried doing some thing like this and it throws an error in the web browser console saying it can't find my controllers. Any hints?

I searched StackOverflow and found this similar question - however, this syntax is using a different framework (CoffeeScript) on top of Angular, and so I haven't been able to follow.


AngularJS: How do I create controllers in multiple files


Source: (StackOverflow)

Multiple types were found that match the controller named 'Home'

I currently have two unrelated MVC3 projects hosted online.

One works fine, the other doesn't work, giving me the error:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request.

If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

The way my hoster works is that he gives me FTP access and in that folder I have two other folder, one for each of my applications.

ftpFolderA2/foo.com

ftpFolderA2/bar.com

foo.com works fine, I publish my application to my local file system then FTP the contents and it works.

When I upload and try to run bar.com, the issue above fires and prevents me from using my site. All while foo.com still works.

Is bar.com searching from controllers EVERYWHERE inside of ftpFolderA2 and that's why it's finding another HomeController? How can I tell it to only look in the Controller folder as it should?

Facts:

  1. Not using areas. These are two COMPLETELY unrelated projects. I place each published project into each respective folder. Nothing fancy.
  2. Each project only has 1 HomeController.

Can someone confirm this is the problem?


Source: (StackOverflow)

Can I get the name of the current controller in the view?

Is there a way to figure out what the current controller is from within the view?

For an example of why I would want to know this: if several controllers share the same layout, I may have a part in the layout ERB file where I want to highlight the current page's menu item based on the controller.

Maybe that is a bad approach. If so, what is the more preferred way to do this?

I'm interested to know about getting the name of the current controller either way, though.

(Obviously I could put something like @controller_name = 'users' in each controller; but that seems like the sort of thing Rails would've already done behind the scenes. So I'm just wondering if there's a built-in way.)


Source: (StackOverflow)

Is it possible to determine whether ViewController is presented as Modal?

Is it possible to check inside ViewController class that it is presented as modal view controller?


Source: (StackOverflow)

Init method in Spring Controller (annotation version)

I'm converting a controller to the newer annotation version. In the old version I used to specify the init method in springmvc-servlet.xml using:

<beans>
    <bean id="myBean" class="..." init-method="init"/>
</beans>

How can I specify the init method using the annotation version?


Source: (StackOverflow)

ASP.NET MVC - Should business logic exist in controllers?

Derik Whitaker posted an article a couple of days ago that hit a point that I've been curious about for some time: should business logic exist in controllers?

So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.


Source: (StackOverflow)

Which is better, return "ModelAndView" or "String" on spring3 controller

The way of return ModelAndView

@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(
    @UserAuth UserAuth user, 
    ModelAndView mav) {

    if (!user.isAuthenticated()) {
        mav.setViewName("redirect:http://www.test.com/login.jsp");
        return mav;
    }

    mav.setViewName("list");
    mav.addObject("articles", listService.getLists());

    return mav;
}

The way of return String

@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(
    @UserAuth UserAuth user, 
    Model model) {

    if (!user.isAuthenticated()) {
        return "redirect:http://www.test.com/login.jsp";
    }

    model.addAttribute("articles", listService.getLists());

    return "list";
}

These work same. which is better way? and what is difference?


Source: (StackOverflow)

Get controller and action name from within controller?

For our web application I need to save the order of the fetched and displayed items depending on the view - or to be precise - the controller and action that generated the view (and the user id of course, but that's not the point here).

Instead of just giving an identifier myself in each controller action (in order to use it for some view-dependant sorting of DB outputs), I thought that it would be safer and easier to create this identifier automatically from the controller and action method it gets called from.

How can I get the name of the controller and action from within the action method in a controller? Or do I need reflection for that? I guess it's pretty easy, thanks in advance!


Source: (StackOverflow)

Fat models, skinny controllers and the MVC design pattern

I just read a blog post that explains MVC with a banking analogy. I have a few months of experience with web application development with an MVC framework (CakePHP), so I get the basics, but I began to see a theme that made me think I'm taking a flawed approach to where I put my logic:

  • Fat models, skinny controllers
  • Keep as much business logic in the models as possible

In my app, models are anorexic and controllers are obese. I have all business logic in the controllers and nothing besides associations and validation rules in the models.

Scanning through my controllers, I can now identify a lot of logic that should probably go in a model:

  • The app has lists, which contain items, and the items can be ranked. The sorting logic which puts the list in ranked order is in a controller.
  • Similarly, items (Item model) also have images (Image model). Each item may have a default image (designated by image_id in the items table). When an item is displayed with its images, the default image should appear first. I have the logic that does this in a controller.
  • When a list is displayed, related lists are displayed in the sidebar. The logic to determine which lists are related is in a controller.

Now to my questions:

  1. With the examples I gave above, am I on the right track in thinking that those are instances of logic presently in a controller that belongs in a model?
  2. What are some other areas of logic, common to web apps, that should go into models?
  3. I'm sure identifying this problem and changing my design pattern is half the battle, but even if I decide to take those examples I gave above and try to move that logic to a model, I wouldn't know where to begin. Can anyone point me in the right direction by posting some code here, or linking to some good learning resources? CakePHP specific help would be great, but I'm sure anything MVC will suffice.

Source: (StackOverflow)