Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing views between controllers without using the Shared folder

Lets say I have a controller which provides search functions for a student:

public class StudentSearchController
{
    [HttpGet]
    public ActionResult Search(StudentSearchResultModel model)
    {
        return View(model);
    }
}

So long as the Search action is provided a StudentSearchResultModel, it will render a list of search results.

Is there a way to effectively extend this action method from another controller? For example, lets say I want to have other controllers that need to search for students, like this:

public class UniStudentController
{
    [HttpPost]
    public ActionResult Search(UniStudentSearchResultModel model)
    {
        return RedirectToAction("Search", "StudentSearch", model);
    }
}

public class HighSchoolStudentController
{
    [HttpPost]
    public ActionResult Search(HighSchoolSearchResultModel model)
    {
        return RedirectToAction("Search", "StudentSearch", model);
    }
}

(presuming both models extend StudentSearchResultModel.)

I obviously can't do this, because I can't pass the pre-instantiated model classes to the search controller (the original search controller will recreate a StudentSearchResultModel, rather than using the model that was passed).

The best solution I've come up with so far is to move SearchView.cshtml into the "Shared" folder, then I can just render the view from the Uni/HighSchool controllers directly (instead of calling "RedirectToAction"). That works just fine, and in theory I wouldn't need the StudentSearchController at all. However, I'm building on legacy code here (in this contrived example, StudentSearchController is legacy), so without doing a boatload of refactoring, the "Shared" folder isn't an option for me.

Another solution would be to put all search related actions into the StudentSearchController - so it would get two actions for UniStudentSearch and HighSchoolStudentSearch. I don't like this approach though, as it means that the StudentSearchController needs to know about all of its intended usages.

Any ideas?

PS: Not opposed to the refactoring, but am limited by deadlines!

like image 956
gerrod Avatar asked Feb 09 '12 04:02

gerrod


1 Answers

you can put the path of the view in your call to View()

return View("~/Views/StudentSearch/SearchView.cshtml", model);
like image 147
Stafford Williams Avatar answered Sep 27 '22 21:09

Stafford Williams