Rusi Nova
Rusi Nova

Reputation: 2655

How to Return Helpers Text as data from Action

I have created a following helper (below codes are just to demonstrate what I am looking for)

@helper SayHello(string text)
{
   @text
}

Now from an action i want to return this Helper's Text as Html (or string) as below

public ActionResult MyAction()
{
      //something like this to return just html
      return SayHello("Rusi");
}

Upvotes: 0

Views: 139

Answers (2)

Ofer Zelig
Ofer Zelig

Reputation: 17498

I don't know if this is possible, but even if so - PLEASE DO NOT DO THAT! It so much breaks MVC's separation architecture.

Instead, implement the SayHello helper in, say, a .cshtml file which is being called by an action method (you should decorate your action method in a [ChildActionOnly] attribute), and then you invoke the action method from within your Razor pages by using @Html.Action() or @Html.RenderAction().

Upvotes: 1

Iridio
Iridio

Reputation: 9271

AFAIK You can not return a simple string as an actionresult method. Instead you should call your function from ajax and handle the returning text via javascript/jquery. Otherwise you can return a view containig your string like a model. Something like that

return View(SayHello("hello world"));

Upvotes: 0

Related Questions