Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

JSON calling C# class method

Trying to call a C# class from JSON.

The JSON code is in my master.cshtml file, and looks like this:

var tips = $(".validateTips");

function updateTips(t) {
   tips
   .text(t)
   setTimeout(function () {
      tips.removeClass("ui-state-highlight", 1500);
   }, 500);
}

$.ajax({
   type: "POST",
   url: "/App_Code/LoginClass.cs/test",
   data: {},
   contentType: "application/json; charset=utf-8",
   datatype: "JSON",
   success: function (msg) {
      updateTips(msg.d);
   }
});

the C# code is in the file LoginClass.cs and looks like this:

public class LoginClass
{
    public static string test()
    {
         return "hello";
    }
}

my solution folders looks like this:
+----App_Code
|    |
|    +---LoginClass.cs
|
+----Views
|    |
|    +---Shared
|        |
|        +---Master.cshtml
|
+----default.cshtml (Where the master layout page is connected to)

The updateTips doesn't

Upvotes: 0

Views: 1607

Answers (2)

Mario S
Mario S

Reputation: 11945

I'm afraid you can't call code like that in ASP.NET MVC. You need to go through a Controller first.

Begin by creating a controller, usually in the Controllers folder in the project root:

public class LoginController : Controller // Inherit from Controller base class.
{
    // An action on the controller that you can call.
    [HttpPost] // Use HttpPost to limit only to POST requests.
    public ActionResult Test()
    {
        // Use your class here to get values.
        string value = LoginClass.test();

        // Return a JSON result that converts your object to JSON for you.
        return Json(value);
    }
}

And then call the action like so (according to a part of the default route pattern {Controller}/{Action} in global.asax):

$.ajax({
   type: "POST",
   url: "/Login/Test", // Notice the new path. ("Controller" is always subtracted from a controller name: "LoginController" > "Login".)
   data: {},
   contentType: "application/json; charset=utf-8",
   datatype: "JSON",
   success: function (msg) {
      updateTips(msg.d);
   }
});

If you want to use JSON without POST:

public ActionResult Test()
{
    string value = LoginClass.test();
    return Json(value, JsonRequestBehavior.AllowGet);
}

Upvotes: 3

SBurris
SBurris

Reputation: 7448

When you make an AJAX call to an MVC application, you still need to go through a controller.

In the Controller Folder create a Controller Class (Ctrl+M, Ctrl+C) called AccountController and add the following method:

public class AccountController : Controller
{
  [HttpPost]
  public ActionResult Test()
  {
    return Json("hello");
  }
}

Javascript Call:

$.ajax({
   type: "POST",
   url: "/Login/test",
   data: {},
   contentType: "application/json; charset=utf-8",
   datatype: "JSON",
   success: function (msg) {
      updateTips(msg.d);
   }
});

Upvotes: 5

Related Questions