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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With