在ASP.Net Core MVC中使用Ajax请求并返回JSON响应的解决方法如下:
首先,确保你的项目已经引用了Microsoft.AspNetCore.Mvc和Microsoft.AspNetCore.Mvc.ViewFeatures包。
在Controller中创建一个方法,该方法将处理Ajax请求并返回JSON响应。你可以使用[HttpPost]或[HttpGet]属性来指定请求类型。例如:
[HttpPost]
public IActionResult AjaxRequest()
{
// 处理Ajax请求的逻辑
// 创建一个包含要返回的数据的对象
var data = new { Name = "John", Age = 30, City = "New York" };
// 返回JSON响应
return Json(data);
}
$.ajax({
url: '/ControllerName/AjaxRequest',
type: 'POST', // 或者 'GET',根据你的Controller方法而定
dataType: 'json',
success: function(response) {
// 处理JSON响应
console.log(response.Name);
console.log(response.Age);
console.log(response.City);
},
error: function(error) {
console.log(error);
}
});
在上述代码中,将'/ControllerName/AjaxRequest'替换为你的Controller和方法的实际路由。
这样,当你在页面中触发Ajax请求时,它将向服务器发送请求,并返回一个JSON响应。在成功回调函数中,你可以处理返回的JSON数据。