gpt4 book ai didi

ajax - .NET Core 从 Razor 页面到 Controller 进行 AJAX 调用

转载 作者:行者123 更新时间:2023-12-04 14:55:42 26 4
gpt4 key购买 nike

我有一个使用 Razor Pages 的 .NET Core 3.1 项目。从中我创建了一个简单的测试,我可以使用以下代码进行成功的 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 移到 Controller 中,以便我可以从多个 Razor Pages 调用它。我使用以下代码创建了一个 Controller :
public class AjaxController : Controller
{
public JsonResult Test()
{
return new JsonResult("Ajax Test");
}
}

Startup.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 errorControllers 文件夹需要在 Pages 目录下吗?或者我是否需要配置一些路由来使用 ControllerRazor Pages
url: "/Ajax/Test" // <-- What goes here?

这是当前的目录结构:

enter image description 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?}");
});

显示 Controller .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>

关于ajax - .NET Core 从 Razor 页面到 Controller 进行 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59788897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com