PixelPaul
PixelPaul

Reputation: 2767

.NET Core making an AJAX call from a Razor Page to a Controller

I have a .NET Core 3.1 project using Razor Pages. From it I created a simple test where I am able to make a successful Ajax call with the following code:

Index.cshtml.cs

public class IndexModel : PageModel
{
    public void OnGet()
    {

    }

    public JsonResult OnGetTest()
    {
        return new JsonResult("Ajax Test");
    }
}

Index.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>

However, I would like to move the Ajax method out of the Razor Page and into to a Controller so I could call it from from multiple Razor Pages. I have created a controller using the following code:

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();
        });
    }
}

But whatever value I use in the url for the Ajax call, I get a 404 error. Does the Controllers folder need to be in the Pages directory? Or do I need to configure some routing to use a Controller with Razor Pages?

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

Here is the current directory structure:

enter image description here

Upvotes: 4

Views: 3705

Answers (2)

Asherguru
Asherguru

Reputation: 1741

In Startup.cs, add this to ConfigureServices()

services.AddMvc(options => options.EnableEndpointRouting = false);

In Startupcs, also add this to Configure()

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

DisplayController.cs

public IActionResult Test()
    {
        return new JsonResult("Hi World");
    }

Index.cshtml

<a onclick="ClickMe();">Click Me</a>
<script>
function ClickMe() {
    $.get("/Display/Test", null, function (e) {
        alert(e);
    });
}
</script>

Upvotes: 4

Peter B
Peter B

Reputation: 24136

You need to specify a Route attribute, like this:

[Route("api/Ajax")]
public class AjaxController : Controller
{
    // ...
}

It is also best to decorate each individual endpoint with a 'Method' attribute, like this:

[HttpGet]
public JsonResult Test()
{
    return new JsonResult("Ajax Test");
}

Furthermore you also need to set the correct configuration in Startup.cs as shown below, add all the parts that you do not have:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    });
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // lots of stuff...

    // I have this after app.UseStaticFiles(), it may also work elsewhere
    app.UseMvcWithDefaultRoute();

    // lots of other stuff...
}

And then you should be able to call it using the path /api/Ajax/Test.

Upvotes: 1

Related Questions