asp.netajaxasp.net-corerazor-pagesasp.net-core-viewcomponent

Asp.NET core, AJAX doesn't work at all in my project


I started a Razor Pages project and I need to use AJAX so that I can refresh my comments section without refreshing my entire page. unfortunately AJAX does not seem to work at all, it's as if the code was never there.

I thought it was just because I couldn't connect my buttons to the script, but even the code that's supposed to run upon (document).ready does nothing. So I am at a loss.

here is some test code I'm trying to run:

<button id="buttonDemo1" >THE AJAX BUTTON</button>


@section Scripts
    {
    <script >
        //edit: threw console.log around, nothing shows up in the browser console

        $(document).ready(function () {
            console.log("ready2!!");

            var url = '@Url.Action("TEST", "ChatRoom")';

            $('#buttonDemo1').click(function () {

                console.log("THE FORBIDDEN BUTTON HAS BEEN PRESSED!");
                $.ajax({
                    type: 'GET',
                    url: url,
                    success: function (result) {
                        alert("ajax success");
                    }
                });
            });
        });


        $(document).ready(function(){

        

            
            console.log("ready!!");

            $.ajax({
                type: "POST",
                url: '@Url.Action("TEST", "ChatRoom")',
                data: {
                    },
                success: function (response) {
                    console.log("success");
                    alert("ajax success")
                },
                failure: function () {
                    console.log("fail");
                    alert("ajax fail");

                },
                error: function (response) {
                    console.log("error");
                    alert(response.responseText)
                }
            });


        }


    </script>
}

Here is my Program.cs:

using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Scratch.Data;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(
    options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddMvc();

builder.Services.AddRazorPages();




builder.Services.Configure<IdentityOptions>(options =>
{

    

    // Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;

    // Lockout settings.
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;

    // User settings.
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});


//this forces authorisation to be required on all pages that don't have the [AllowAnonymous] tag
/*builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});*/




var app = builder.Build();





// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
    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.UseRouting();

app.UseAuthentication();;

app.UseAuthorization();

app.MapRazorPages();

//trying to add mvc to the project
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    //chathub doesn't exist
    //endpoints.MapHub<ChatHub>("/chathub");
    endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
});




app.Run();

I must be missing something critical, do I need to install some NuGet package, or is there something I need to add to my Program.cs file? Any suggestions would be much appreciated.


Solution

  • I couldn't connect my buttons to the script, but even the code that's supposed to run upon (document).ready does nothing. So I am at a loss.

    The way you are trying to call your button event is incorrect; so your functionality shouldn't work in this fashision for sure because you are using $(document).ready(function() twice within the same script section and this causing the issue.

    I must be missing something critical, do I need to install some NuGet package, or is there something I need to add to my Program.cs file?

    No, you don't need any nuget package or any middleware referece within your prgram.cs file. You can resolve your issue by ommiting one additional $(document).ready section.

    Solution:

    You should use single $(document).ready(function() within the script and within that block you should please your all the function. You can try as following:

    HTML:

     button id="buttonDemo1">THE AJAX BUTTON</button>
    

    Script:

    @section Scripts
        {
        <script>
            //edit: threw console.log around, nothing shows up in the browser console
    
            $(document).ready(function () {
                alert("Click");
                console.log("ready2!!");
    
                var url = '@Url.Action("TEST", "ChatRoom")';
    
                $('#buttonDemo1').click(function () {
                      alert("buttonDemo1 Click");
                    console.log("THE FORBIDDEN BUTTON HAS BEEN PRESSED!");
                    $.ajax({
                        type: 'GET',
                        url: url,
                        success: function (result) {
                            alert("ajax success");
                        }
                    });
                });
            });
    
        </script>
    }
    

    Note: Your second ajax functional seems doing nothing so I haven't included that. If you need that you can include that within the same document.ready function but in another function block.

    Output:

    enter image description here