首页 > 解决方案 > .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();
        });
    }
}

但是无论我在urlAjax 调用中使用什么值,我都会得到一个404 error. 文件夹是否Controllers需要在Pages目录中?还是我需要配置一些路由来使用Controllerwith Razor Pages

url: "/Ajax/Test" // <-- What goes here?

这是当前目录结构:

在此处输入图像描述

标签: ajax.net-corerazor-pages

解决方案


在 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>

推荐阅读