Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Simple Class and Call Its Method from a cshtml File without using App_Code

Tags:

c#

asp.net

razor

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.

like image 525
Shaun Luttin Avatar asked Nov 28 '25 04:11

Shaun Luttin


2 Answers

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

@using ProjectName;

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

like image 61
Ken Spur Avatar answered Nov 29 '25 17:11

Ken Spur


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.

like image 25
Gowtham.K.Reddy Avatar answered Nov 29 '25 17:11

Gowtham.K.Reddy