Setting up the Environment:
<package id="jQuery" version="3.2.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
Recently, I encountered an issue while trying to send a request from one of my JavaScript files to methods in a C# file. Despite receiving a 200 OK response, the content returned was empty and when using console.log(response)
, it showed undefined
. Could this problem be related to the requesting URL or did I make an error in defining my C# function? Any suggestions or assistance would be greatly valued!
Below is the snippet of my JavaScript code:
<script>
console.log("hello_List!")
function getSearch() {
console.log($("#query").val())
console.log(typeof($("#query").val()))
$.ajax({
type: "POST",
url: "./Search",
data: $("#query").val(),
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert("Success!");
console.log(response);
}
</script>
Here is my C# function, located in the same folder as my JavaScript file:
public class UsersController : Controller
{
[HttpPost]
[System.Web.Services.WebMethod]
public JsonResult Search(string query)
{
List<EntityModels.AspNetUser> users = new List<EntityModels.AspNetUser>();
users = db.AspNetUsers.Where(x => x.Email.StartsWith(query)).ToList();
List<SelectListItem> userObjs = new List<SelectListItem>();
foreach (var user in users)
{
var userObj = new SelectListItem
{
Value = user.Id.ToString(),
Text = user.Email
};
userObjs.Add(userObj);
}
return new JsonResult()
{
Data = userObjs,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
}