Asp.net-mvc – Calling non-Action methods from view-MVC .NET

asp.net-mvcasp.net-mvc-4

I want to call a non-action method in a view. Can I do that? In other words, there is a method in my controller which returns a string. I want to call that method in my view (.cshtml) and show it in the view. All I could see was, the methods should return an ActionResult. But in my case I do not need a view returned just a string.

Best Answer

The best way (and MVC convention way) to do this is to use a ViewModel. Quick example:

Model

public class MyViewModel {
    public string StringValue { get; set; }
}

Controller

public class MyController : Controller 
{
    public ActionResult MyView() 
    {
        var model = new MyViewModel
        {
            StringValue = CallMyMethod()
        }

        return View(model);
    }
}

View

@model MyViewModel @*(use fully qualified namespace)*@

@Model.StringValue @*<-- this will print it out on the view*@

Hope that helps!