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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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.…

730 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