[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
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…

650 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