如何在 ASP.NET Core 中从 Javascript 调用 C# 方法?

Dav*_*ave 5 html c# asp.net-core

我的Index.cshtml文件中有一个用户名文本框,每当用户更改文本框中的文本时,我想检查 Active Directory 中的匹配项,然后可能将其显示在 中DropDownList,以便用户可以从其中进行选择。
因此,我在文本框事件上调用 JavaScript 函数oninput,现在的问题是如何从该 JS 函数调用我的 C#FindUser()方法Index.cshtml.cs?我已经尝试了很多我读过的内容,ajax调用不起作用,添加方法[WebMethod]并使方法静态不起作用,并且互联网上的大多数都是我没有使用的 MVC。

文本框位于Index.cshtml

<input type="text" class="form-control" oninput="findUsers()" />
Run Code Online (Sandbox Code Playgroud)

JavaScript 函数:

function findUsers() {
  $.ajax({
    url: 'Index\FindUser',
    success: function (data) {
      alert(data);
    },
    error: function (error) {
      alert("Error: " + error);
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

导致浏览器报警

错误:[对象对象]

Index.cshtml.cs中的方法:

public void FindUser()
{
  // code            
}
Run Code Online (Sandbox Code Playgroud)

该方法甚至不是从 JS 函数中调用的。
另外,我也读过几次,从视图调用 C# 方法并不是正确的方法。如果是的话,我怎样才能实现我的目标呢?

Amm*_*mar 8

我发现您正在使用 Razor 页面。razor 页面模型中的方法不是路由方法(无法通过请求路由来调用),这就是为什么尝试向 发送请求ajax不起作用Index\FindUser,服务器返回的错误将是 404 not find。

或者,您可以使用 Razor 页面处理程序。

Index.cshtml.cs如果该方法是异步方法,则将该方法重命名FindUser()OnGetFindUser()or 。OnGetFindUserAsync()

然后,您可以通过向 发送请求来调用此方法"Index?handler=FindUser"

// Note the difference in method name
public IActionResult OnGetFindUser()
{
    return new JsonResult("Founded user");          
}
Run Code Online (Sandbox Code Playgroud)
function findUsers() {
  $.ajax({
    type: 'GET',
    // Note the difference in url (this works if you're actually in Index page)
    url: '?handler=FindUser',
    success: function (data) {
      alert(data);
    },
    error: function (error) {
      alert("Error: " + error);
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

进一步建议阅读