ajax - .NET Core 从 Razor 页面向控制器进行 AJAX 调用
问题描述
我有一个使用 .NET Core 3.1 的项目Razor Pages
。通过它,我创建了一个简单的测试,我可以使用以下代码进行成功的 Ajax 调用:
索引.cshtml.cs
public class IndexModel : PageModel
{
public void OnGet()
{
}
public JsonResult OnGetTest()
{
return new JsonResult("Ajax Test");
}
}
索引.cshtml
@page
@model IndexModel
<div class="text-center">
<p>Click <a href="#" onclick="ajaxTest()">here</a> for ajax test.</p>
</div>
<script type="text/javascript">
function ajaxTest() {
$.ajax({
type: "GET",
url: "/Index?handler=Test",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
console.log(error);
}
}).done(function (data) {
console.log(data);
});
}
</script>
但是,我想将 Ajax 方法移出Razor Page
并移入 aController
以便我可以从 multiple 调用它Razor Pages
。我使用以下代码创建了一个控制器:
public class AjaxController : Controller
{
public JsonResult Test()
{
return new JsonResult("Ajax Test");
}
}
启动.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
但是无论我在url
Ajax 调用中使用什么值,我都会得到一个404 error
. 文件夹是否Controllers
需要在Pages
目录中?还是我需要配置一些路由来使用Controller
with Razor Pages
?
url: "/Ajax/Test" // <-- What goes here?
这是当前目录结构:
解决方案
在 Startup.cs 中,将其添加到 ConfigureServices()
services.AddMvc(options => options.EnableEndpointRouting = false);
在 Startupcs 中,也将其添加到 Configure()
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
显示控制器.cs
public IActionResult Test()
{
return new JsonResult("Hi World");
}
索引.cshtml
<a onclick="ClickMe();">Click Me</a>
<script>
function ClickMe() {
$.get("/Display/Test", null, function (e) {
alert(e);
});
}
</script>
推荐阅读
- pandas - 日期时间索引数据帧日志时间刻度(x 轴)绘图
- android - 安卓。WindowBackground 中心图标不像活动图标那样居中
- c# - 如何从后面的代码中设置 html 输入日期标签的值
- python - python和pyqt5 - 单击按钮后传递变量
- javascript - 无法让 alignItems 在 React 中工作
- c - C: 文件 I/O - 来自书籍与现实的代码示例。省略.txt?
- java - 在链表中拆分值
- javascript - 关于 FIREBASE => Angular , 当我们使用 Push 方法写入数据时如何读取 FIREBASE 中的数据
- python - From fancyimpute import KNN - 如何安装包
- powershell - Powershell Return-Job 有时会返回空值