Solved

Asp.net MVC shared method

Posted on 2013-11-22
3
526 Views
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;
            GenreLst.AddRange(GenreQry.Distinct());
            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);
            else
            {
                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.

Joe
0
Comment
Question by:dataflowjoe
3 Comments
 
LVL 16

Accepted Solution

by:
Stephan earned 300 total points
Comment Utility
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;
    GenreLst.AddRange(GenreQry.Distinct());
    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.
0
 
LVL 22

Assisted Solution

by:ambience
ambience earned 200 total points
Comment Utility
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.
0
 
LVL 2

Author Closing Comment

by:dataflowjoe
Comment Utility
Thanks guys
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
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…
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…

763 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now