简体   繁体   English

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

[英]How to call C# method from Javascript in ASP.NET Core?

I have a username textbox in my Index.cshtml file and I want to check for matches in our Active Directory whenever the user changes the text inside the textbox and then maybe display it in a DropDownList , so the user can choose form it.我的Index.cshtml文件中有一个用户名文本框,我想在用户更改文本框内的文本时检查我们的 Active Directory 中的匹配项,然后可能将其显示在DropDownList ,以便用户可以选择它。
So I call a JavaScript function on the oninput event of the textbox and now the question is how do I call my C# method FindUser() in Index.cshtml.cs from that JS function?所以我在文本框的oninput事件上调用了一个 JavaScript 函数,现在的问题是我如何从那个 JS 函数调用我在Index.cshtml.cs C# 方法FindUser() I have tried a lot of what I've read, ajax call doesn't work, adding [WebMethod] and making the method static doesn't work and most on the internet is on MVC which I'm not using.我已经尝试了很多我读过的内容, ajax调用不起作用,添加[WebMethod]并使方法静态不起作用,并且互联网上的大多数都在我没有使用的 MVC 上。

Textbox in Index.cshtml : Index.cshtml文本框:

<input type="text" class="form-control" oninput="findUsers()" />

JavaScript function: JavaScript 函数:

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

leads the browser to alert使浏览器发出警报

Error: [object Object]错误:[对象对象]

Method in Index.cshtml.cs: Index.cshtml.cs 中的方法:

public void FindUser()
{
  // code            
}

The method is not even called from the JS function.该方法甚至不会从 JS 函数中调用。
Also I've read a few times that calling a C# method from the view is not the proper way of doing it.我也读过几次,从视图调用 C# 方法不是正确的方法。 If so, how can I achieve my goal then?如果是这样,我怎样才能实现我的目标?

I see you're using Razor pages.我看到您正在使用 Razor 页面。 A method in razor page model is not a routed method (it can't be called by requesting a route), and that's why trying to send an ajax request to Index\\FindUser won't work, and the error returned by server would be 404 not found. razor 页面模型中的方法不是路由方法(不能通过请求路由来调用),这就是为什么尝试向Index\\FindUser发送ajax请求不起作用,服务器返回的错误将是404 未找到。

Alternatively you can use razor page handlers.或者,您可以使用剃刀页面处理程序。

In your Index.cshtml.cs rename the method FindUser() to OnGetFindUser() or OnGetFindUserAsync() if the method is an asynchronous method.在您的Index.cshtml.cs如果方法是异步方法, OnGetFindUser()方法FindUser()重命名为OnGetFindUser()OnGetFindUserAsync()

You can then call this method by sending a request to "Index?handler=FindUser" .然后,您可以通过向"Index?handler=FindUser"发送请求来调用此方法。

// Note the difference in method name
public IActionResult OnGetFindUser()
{
    return new JsonResult("Founded user");          
}
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);
    }
  })
}

Further suggested read 进一步建议阅读

I am not very experienced yet, I have only started programming last year, but I hope I can help a little bit.我还不是很有经验,我去年才开始编程,但我希望我能帮上一点忙。

I also had a similar problem, but I could not execute a function directly from JavaScript.我也有类似的问题,但我无法直接从 JavaScript 执行函数。 You could maybe create an API call to C# and make the API execute the function you want, and then return the data back to the client.您可以创建对 C# 的 API 调用并使 API 执行您想要的函数,然后将数据返回给客户端。

If I don't misunderstand, you want the user to type some text, and then return from your database a list based on the typed text.如果我没有误解,您希望用户输入一些文本,然后根据输入的文本从数据库返回一个列表。

You could use an onChange in the input tag, and each time it changes, it executes an API request to the server, which will search whatever you need and return it as a json.您可以在 input 标签中使用 onChange ,每次更改时,它都会向服务器执行 API 请求,服务器将搜索您需要的任何内容并将其作为 json 返回。 Then in JavaScript, you parse the data and put it in a select tag.然后在 JavaScript 中,解析数据并将其放入 select 标记中。

Hope it helps.希望能帮助到你。

Ok so first off, you are calling jquery inside javascript function.好的,首先,您正在 javascript 函数中调用 jquery。

Calling a controller action method from ajax is pretty easy.从 ajax 调用控制器操作方法非常简单。

https://api.jquery.com/jquery.ajax/ https://api.jquery.com/jquery.ajax/

You need to determine the request type, the url, the datatype returned, parameters passing etc and then set a breakpoint on the controller action and on the ajax request success and error functions.您需要确定请求类型、url、返回的数据类型、传递的参数等,然后在控制器操作和 ajax 请求成功和错误函数上设置断点。 Then you will be able to see why it has succeeded or failed.然后您将能够看到它成功或失败的原因。

The way i would do it would be to give the input an id, then when a user types text catch the event.我会这样做的方式是给输入一个 id,然后当用户输入文本时捕获事件。

https://api.jquery.com/category/events/ https://api.jquery.com/category/events/

Don't confused jquery and javascript.不要混淆 jquery 和 javascript。

Jquery is a framework that packs javascript inside it. Jquery 是一个将 javascript 封装在其中的框架。

Javascript is the native language. Javascript 是母语。

Change your API like this:像这样更改您的 API:

public bool FindUser(string value)
{
    if (value == "Joe")
        return true;
    else
        return false;
}

Then call it like this:然后像这样调用它:

 <script type="text/javascript"> function findUsers() { var value = document.getElementById("value").value; $.ajax({ type: 'GET', url: '/Home/FindUser, data: value, dataType: 'json', success: function (data) { alert(data); }, error: function (error) { alert(error); } }); } </script>
 <br /> <input type="text" class="form-control" id="value" oninput="findUsers()" />

You can use onkeyup or onblur like this您可以像这样使用 onkeyup 或 onblur

onblur: When you leave the input field, a function is triggered onblur:当你离开输入框时,一个函数被触发

onkeyup: A function is triggered when the user releases a key in the input field onkeyup:当用户在输入字段中释放一个键时触发一个函数

Then modify your code like this然后像这样修改你的代码

html file: html文件:

<input type="text" class="form-control" id="username" oninput="findUsers()" />

js js

function findUsers() {
    var username= document.getElementById("username").value;
    $.ajax({
        type: 'GET',
        url: '/Home/FindUser
        dataType: 'json',
        data: {username},
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

You must return something like this.你必须返回这样的东西。 You are using void keyword so it will not return anything to FE side您正在使用 void 关键字,因此它不会向 FE 端返回任何内容

public JsonResult FindUser(string username)
{
    var object = {
     // something here
    }
    return Json(object);
}

you can call method exactly you want with small addition to Index.cshtml.您可以通过对 Index.cshtml 的少量添加来准确地调用您想要的方法。 First line may be:第一行可能是:

@page "{handler?}"

then call from ajax:然后从ajax调用:

url:'/index/FindUser'

in Index.cshtml.cs calling method:在 Index.cshtml.cs 调用方法中:

void  OnGetFindUser(){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM