Asp.net MVC shared method

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

I'm dabbling with ASP.net 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 1200 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 800 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 http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application 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

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

WHY MVC is the future technology... As many of you know, MVC is Model,View,Controller pattern. Model View Controller pattern was invented in a Smalltalk context at Xerox in late 1970s. Why is this buzz about MVC: --------------------------- …
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
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. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

770 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