0

试图从 JSON 调用 C# 类。

JSON 代码在我的 master.cshtml 文件中,如下所示:

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);
   }
});

C# 代码位于 LoginClass.cs 文件中,如下所示:

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)

更新提示没有

4

2 回答 2

5

当您对 MVC 应用程序进行 AJAX 调用时,您仍然需要通过控制器。

Controller文件夹中创建一个名为 AccountController 的控制器类(Ctrl+M、Ctrl+C)并添加以下方法:

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

Javascript 调用:

$.ajax({
   type: "POST",
   url: "/Login/test",
   data: {},
   contentType: "application/json; charset=utf-8",
   datatype: "JSON",
   success: function (msg) {
      updateTips(msg.d);
   }
});
于 2012-11-08T13:13:22.923 回答
3

恐怕你不能在 ASP.NET MVC 中调用那样的代码。你需要通过Controller第一个。

首先创建一个控制器,通常在项目根目录的Controllers文件夹中:

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);
    }
}

然后像这样调用动作(根据{Controller}/{Action}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);
   }
});

如果你想在没有 POST 的情况下使用 JSON:

public ActionResult Test()
{
    string value = LoginClass.test();
    return Json(value, JsonRequestBehavior.AllowGet);
}
于 2012-11-08T13:26:28.190 回答