December 30 2013

ASP.net add class to App_Code folder

Tagged Under :

asp.net
In ASP MVC4 Appliction I can add a cshtml file in app_code folder like below so that I can use my custom helper method in another cshtml.

App_Code/MyHelpers.cshtml
@helper LabelExtensions(string input) {
    "<pre>@input</pre>"
}

Using the Helper in a Page.
<p>This is some paragraph text.</p>
@MyHelpers.LabelExtensions("My Test Label.")
<p>This is some paragraph text.</p>

Output:
<p>This is some paragraph text.</p>
<pre>My Test Label.</pre>
<p>This is some paragraph text.</p>

But if the helper is classes (cs file) then you are not allow call the helper function like above. Below example show you how to use it in a Page.

App_Code/MyClass.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1 {
  public static class MyClass {

    public static string LabelExtensions(string input) {
      return "<pre>@input</pre>";
    }
  }
}

Using the Classes in a Page.
<p>This is some paragraph text.</p>
@MvcApplication1.MyClass.LabelExtensions("My Test Label.")
<p>This is some paragraph text.</p>

Output:
<p>This is some paragraph text.</p>
<pre>My Test Label.</pre>
<p>This is some paragraph text.</p>
Same output, but different way to showing the output.

If you facing an error “CS0103” as below:
Error: CS0103: The name 'MyClass' does not exist in the current context

It was because in front of the function you forgot add the application name.
MvcApplication1.MyClass.LabelExtensions("My Test Label.")

But if you application name is MvcApplication2, then you need change it to MvcApplication2.

Make a Comment

You must be logged in to post a comment.