Calling a method in the controller

22,288

Solution 1

It is considered bad practice for a view to call methods located on a controller. Usually it is a controller action which populates a model and passes this model to the view. If you needed some formatting on this model you could write an HTML helper.

public static class HtmlExtensions
{
    public static IHtmlString Bla(this HtmlHelper<TestModel> htmlHelper)
    {
        TestModel model = htmlHelper.ViewData.Model;
        var value = string.Format("bla bla {0}", model.SomeProperty);
        return MvcHtmlString.Create(value);
    }
}

and in your view:

@Html.Bla()

Solution 2

That would make unit-testing your mvc site very difficult.

Are you needing a partial view maybe? (what are you actually trying to do?)

Share:
22,288
sonic_7
Author by

sonic_7

Updated on April 24, 2020

Comments

  • sonic_7
    sonic_7 about 4 years

    I'm a newbie about ASP.NET MVC 3, but I have a simple question. Is it possible to call a Controller method from an CSHTML (Razor) page?

    Example:

    xxxControl.cs:

    public String Bla(TestModel pModel)
    {
        return ...
    }
    

    index.cshtml:

    @Bla(Model) <-- Error
    

    Thanks.

    Update:

    Thanks @Nathan. This isn't a good idea to do this on this way. The goal is: I need some formatting string for a field of the Model. But where I put the code that return a formatting String in the case?