Matt Dawdy
Matt Dawdy

Reputation: 19717

Call Method in Class from Razor

I've got a method in a class in an App_Code directory in my MVC 4 project. I can call this fine from controllers, but I can't figure out how to call it from an View (.cshtml) file.

namespace LST.App_Code
{
    public static class Utilities
    {
        public static readonly log4net.ILog log = log4net.LogManager.GetLogger("GeneralLog");

From my View, I've tried several things, all along these lines:

@LST.App_Code.Utilities.log.Info("asdf");

When I do that, I receive the following compilation error when trying to load the page:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0433: The type 'LST.App_Code.Utilities' exists in both 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\bd7cb704\59585235\assembly\dl3\3b0ad3ff\ec2b5faa_0b13ce01\mvcroot.DLL' and 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\bd7cb704\59585235\App_Code.cggwncvj.dll'

Source Error:

Line 7: @using (Html.BeginForm()) Line 8: { Line 9:
@(LST.App_Code.Utilities.log.Info("asdf")) Line 10: Line 11:
@Html.AntiForgeryToken()

I've tried the suggestions about cleaning the project, the asp.net temporary files directory, and setting the batch compilation option. Nothing is working.

I'm not that familiar with the intricacies of the Razor syntax. Can someone please point me in the right direction?

Upvotes: 2

Views: 11341

Answers (1)

Hulvej
Hulvej

Reputation: 4215

I make it work with no namespace in the .cs file at all.

If you have created the app_code folder, then you can just create class files like this (without namespaces):

using System:
...

public class FooClass{
  public string Foo(...)
  {
      ...
  }
}

And call it from your view like this:

@{
   new FooClass().Foo(...);

}

Worked for me...

Upvotes: 4

Related Questions