3

I have seen this related question Creating and Simple Class and Calling a Method from a cshtml File. How can we do that without using the App_Code folder?

In my project's root, I have a Something.cs class:

public class Something 
{
    public static void DoIt()  
    { 

    }
}

In my project's root, I also have index.cshtml with the following code:

@Something.DoIt()

The name Something does not exist in the current context of index.cshtml.

Community
  • 1
  • 1
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • `@Something.DoIt()` means you are rendering something, so `DoIt()` method should have return value. By the way, where did you keep Something class? – Win Sep 17 '14 at 00:21

3 Answers3

4

Have you tried to refer the projects library within the cshtml File

@using ProjectName;

Or refer to the object like this @ProjectName.Something.DoIt()

Ken Spur
  • 41
  • 3
1

If you are accessing it on top of .cshtml or inside any HTML string template like for loop then

@{
   MvcDemo.Something.DoIt();
}

Inside BeginForm or the other then

@using (Html.BeginForm())
{
 MvcDemo.Something.DoIt();
}

Please Note MvcDemo is the namespace and if you direclty write @MvcDemo.Something.DoIt() you may get error.

Jon P
  • 19,442
  • 8
  • 49
  • 72
Gowtham.K.Reddy
  • 967
  • 1
  • 9
  • 26
0

Here are the steps that I needed to take.

  1. Create a file called SomeThing.cs.
  2. Place said file anywhere in the csproj root directory.
  3. Add said file to the .csproj (this is what I forgot to do).
  4. Add class SomeThing with method DoIt() to said SomeThing.cs file.
  5. Call its methods from SomeFile.cshtml file.

E.g. SomeFile.cshtml

@SomeThing.DoIt() // this assumes class SomeThing is NOT inside a namespace.

My problem was not adding SomeThing.cs to the .csproj.

Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467