Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Access controller instance from view

How can I access a controller instance from the view? E.g. I have a HomeController which then returns my Index view. Inside of that view I want to access the HomeController instance that created the view. How do I do that?

like image 291
Alex Avatar asked Sep 13 '09 08:09

Alex


People also ask

How do you pass data from controller to view and from view to controller?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can we pass data from view to controller?

Pass value from view to controller using ParameterIn MVC we can fetch data from view to controller using parameter. In MVC View we create html control to take input from the user. With the help of name element of html control we can access these data in controller.


2 Answers

ViewContext.Controller, and you'll need to cast it.

<% var homeController = ViewContext.Controller as HomeController; %> 

This is covered with a few extra wrinkles in post Asp.Net MVC: How do I get virtual url for the current controller/view?.

EDIT: This is to add some meat to Mark Seemann's recommendation that you keep functionality out of the view as much as humanly possible. If you are using the controller to help determine the markup of the rendered page, you may want to use the Html.RenderAction(actionName, controllerName) method instead. This call will fire the action as though it was a separate request and include its view as part of the main page.

This approach will help to enforce separation-of-concerns because the action method redirected to can do all the heavy lifting with respect to presentation rules. It will need to return a Partial View to work correctly within your parent view.

like image 84
David Andres Avatar answered Oct 05 '22 04:10

David Andres


In my opinion, you should consider a design where the View doesn't need to know about the Controller. The idea is that the Controller deals with the request, conjures up a Model and hands that Model off to the View. At that point, the Controller's work is done.

I think it is an indication of a design flaw if the View needs to know anything about the Controller. Can you share more about what it is that you are trying to accomplish?

I often find that when dealing with well-designed frameworks (such as the MVC framework), if it feels like the framework is fighting you, you are probably going about the task in the wrong way. This has happened to me a lot, and stepping back and asking myself what it is that I'm really trying to accomplish often leads to new insights.

like image 27
Mark Seemann Avatar answered Oct 05 '22 04:10

Mark Seemann