views:

58

answers:

3

I have a method in the controller which returns a string.

I need to call this method from my view to get the string and show in the view.

I am using MVC2. how can i call a public method in controller from the View?

+3  A: 

You really shouldn't be calling a method in the controller from the view, that's backwards from the MVC pattern. Controllers call views. You could either pass in the data to the view from the controller as it's called, or this might be a method that belongs in a helper class the view can use.

Edit: Good starter tutorial on helpers if you aren't familiar.

Parrots
Upvoted. Controllers collect data and pass them on to the view. Views don't call controllers.
Brad Wilson
Writing a helper method worked for me
Prasad
A: 

Parrots is right, you shouldn't be accessing a controller from a view (use helpers as he says), but if you must:

<%= ((MyController)this.ViewContext.Controller).SomeMethod() %>
JonoW
A: 

If you need to call something (which view shouldn't do but...) you can provide view with a callback instead of referencing controllers in the view:

ViewData["callback"] = new Func<string>(() => "string");
// or for strongly typed views
Model.Callback = new Func<string>(() => "string");

in view

<%= ((Func<string>)ViewData["callback"])() %>
<%= Model.Callback() %>

But you really better not do this.

queen3