Solved MVC shared method

Posted on 2013-11-22
Last Modified: 2013-11-28
Hi experts,

I'm dabbling with MVC and slowly working through this excellent tutorial . I've got to the point where I've created a lookup list of movie genres which is used for searching the list of movies. I now realise that it would be useful to have the same list when creating or editing a movie. I realise that it is bad practice to recreate the code each time for the routing methods. So how would I organise the code so it is placed in one location and then referenced from there wherever I need it.

        public ActionResult SearchIndex(string movieGenre, string searchString)
            //+++++++++START OF GENRE LIST CREATION+++++++++++++++
            var GenreLst = new List<string>();

            var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;
            ViewBag.movieGenre = new SelectList(GenreLst);
            //+++++++++END OF GENRE LIST CREATION+++++++++++++++

            var movies = from m in db.Movies
                         select m;

            if (!String.IsNullOrEmpty(searchString))
                movies = movies.Where(s => s.Title.Contains(searchString));

            if (string.IsNullOrEmpty(movieGenre))
                return View(movies);
                return View(movies.Where(x => x.Genre == movieGenre));


        public ActionResult Create()
	//++++++I'd like to create the genre list here before being passed
                  //to the create movie view without repeating the section of code 
	//from the searchIndex method above++++++++

            return View();

Open in new window

I'm guessing that I create a public method within the same class and call it from both of the other methods.

Any help would be appreciated.

Question by:dataflowjoe
LVL 16

Accepted Solution

Stephan earned 300 total points
ID: 39671266
Why not creating a method that will return a List<string> containing the genres and invoke this method to fill the viewbag.

public ActionResult GetGenres()
    //+++++++++START OF GENRE LIST CREATION+++++++++++++++
    var GenreLst = new List<string>();
    var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;
    return GenreLst;

Open in new window

And then in the method where you need it:
ViewBag.movieGenre = new SelectList(GetGenres());

Open in new window

It is even better to move this logic to a separate class to have this method available to all controllers.
LVL 22

Assisted Solution

ambience earned 200 total points
ID: 39671285
Since you are in the learning phase, these tutorials are good to get a basic understanding of ASP MVC, however the downside is that in order to keep things simple such tutorials often show coding practices that are not suitable for anything other than just learning. For example, it is a well known concept that Controllers should not contain business or data access logic.

As you just noticed that yourself, you need to be able to better structure your code and logic so as to reuse as much as possible.

I would suggest that you complete the tutorial and then take a look at some other tutorials like that show how to use the Repository and UnitOfWork pattern - much better.

To answer your question directly.

1) If you are facing a situation where you want to reuse Views (with models) then you can take a look at Partial Views, as well as the ability to Render different actions from the View. Take a look at Html.RenderAction for example.

2) As mentioned earlier, business logic should be put into Services and Repositories (think being able to Unit test them separately) and Controllers should only deal with Views, request routing and stuff.

Author Closing Comment

ID: 39684146
Thanks guys

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question