Jimmyt1988
Jimmyt1988

Reputation: 21116

Usual practice for re-usable elements in MVC 5.0 - Visual Studio

I have recently been writing controllers for specific pages... so let's say we have 2 controllers:

HomeController
JamesController

On the Home page, I have a dropdown list that contains all James items... On the James list page, I have a dropdown list that contains all James items...

Evidently, I'm gonna be using the same code to get a full list of James back and present it to a view:

    public ViewResult List()
    {
        IEnumerable<James> jamesList = repository.James();
        return View(jamesList);
    }

What's the usual practice for re-usable bits of code like that? Do you have 2 methods doing the same job where they are required... or do you have ANOTHER called JamesDropDownController and just call upon that from within the 2 views that the 2 controllers are pushing data to?

Upvotes: 0

Views: 41

Answers (1)

Murali Murugesan
Murali Murugesan

Reputation: 22619

I would create JamesDropDownController with GetList action and call it from RenderAction

public class JamesDropDownController 
{
 public ActionResult GetList()
 {
  List<SelectItem> allItems= new List<SelectItem>(); // from DB
  return View("JamesDropDown", allItems);
 }
}

Views/Shared/JamesDropDown.cshtml

@model List<SelectItem>

@Html.DropDownListFor("JamesDropDown",model);

In all the views that required James Drop down

 @Html.RenderAction("GetList","JamesDropDown")

Upvotes: 1

Related Questions