How can I invoke a C# function from JavaScript in an ASP.NET Core application?

I have an input field for a username in my Index.cshtml page, and I want to check for matches in Active Directory every time the user types something in this field. Additionally, I aim to present these matches in a DropDownList to allow user selection.
To trigger this, I’ve set up a JavaScript function for the oninput event of the textbox. My main challenge is calling the C# method SearchForUser() defined in Index.cshtml.cs from the JavaScript function. I attempted various solutions, including ajax requests, and making the method static with the [WebMethod] attribute, but they didn’t work. Most resources I’ve found focus on MVC, which does not apply to my situation.

Here is the textbox in Index.cshtml:


And this is the JavaScript function:
function searchUsers() { $.ajax({ url: ‘Index/SearchForUser’, success: function (response) { alert(response); }, error: function (err) { alert('Error: ’ + err); } }) }

This raises an alert in the browser:

Error: [object Object]


Here is the method in Index.cshtml.cs:
public void SearchForUser() { // implementation code }

It seems the method isn’t being triggered from the JavaScript function. I’ve also learned that calling a C# method directly from a view may not be appropriate. What would be the correct way to achieve this?

It seems like the core issue might lie within configuring the right endpoint and ensuring the correct HTTP method is used. Since you’re working with ASP.NET Core, try to ensure your SearchForUser() method is set as an HTTP endpoint within an ASP.NET Core Controller, and it should return a type like JsonResult or IActionResult. Once set, adjust your AJAX call to point to the correct route with url: '/controller/Index/SearchForUser' and specify type: 'GET' if your server-side method is a GET method. Ensuring the endpoint is correctly defined on your server-side might resolve your current errors, allowing smooth interaction between the client-side JavaScript and your C# methods.

From my experience, one common issue when calling C# methods from JavaScript in ASP.NET Core lies within the routing and method signatures. Ensure your C# method in the controller is asynchronous and returns a JSON result with the HttpGet or HttpPost attribute, depending on what suits your logic best. In your ajax, specify type: 'POST' if your method uses HttpPost, and ensure your URL points correctly to the controller and action name. Importantly, the method may need parameters, which should be correctly serialized from JavaScript. If you’re triggering validation in Active Directory, make sure that the server has permission to access Active Directory services, which can sometimes be a common point of failure. Finally, enabling client-side debugging can sometimes give clearer insights about errors that might not be visible via chrome alerts.