Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

c# - AJAX request in ASP.NET Core 3.1. RazorPages

I am trying to follow this guide: Learn Razor Pages

I get a Http 500 error and this when I try to click the button to do an AJAX Get request:

System.InvalidOperationException: No service for type 'RazorPagesAJAX.Interfaces.CarService' has been registered.

I'm pretty sure I have registered CarService with the code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ICarService, CarService>();
    services.AddRazorPages();
}

On my partial page _CarPartial.cshtml I use

@inject Interfaces.CarService carsList

maybe this is the issue?

I couldn't get the code from the guide

 @model List<Car>

to work.

Any help would be appreciated :)

My code:

Index.cshtml:

@page
@model RazorPagesAJAX.Pages.IndexModel

<divclass="text-center">
    <h1 class="display-4">Razor Pages AJAX Example</h1>
    <p>Main page updated at - @DateTime.Now.</p>
</div>

<h2>Ajax</h2>
<p><button class="btn btn-primary" id="load">Load</button></p>
<div id="grid"></div>
@section scripts{
    <script>
        $(function () {
            $('#load').on('click', function () {
                $('#grid').load('/Index?handler=CarPartial');
            });
        });
    </script>
}

Index.cshtml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using RazorPagesAJAX.Interfaces;                // Import interfaces
using RazorPagesAJAX.Models;                    // Needed to access List of type Car

namespace RazorPagesAJAX.Pages
{
    public class IndexModel : PageModel
    {
        // Dependency injection stuff
        private ICarService _carService;

        // Constructor Injection
        public IndexModel(ICarService carService)
        {
            _carService = carService;
        }

        [BindProperty]
        public List<Car> Cars { get; set; }

        public void OnGet()
        {
        }

        public PartialViewResult OnGetCarPartial()
        {
            Console.WriteLine("Car Partial test");
            Cars = _carService.GetAll();
            return Partial("_CarPartial", Cars);
        }
    }
}

Startup.cs:

namespace RazorPagesAJAX
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // I have added CarService to the Dependency Injection :
            services.AddTransient<ICarService, CarService>();
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

Interface ICarService:

namespace RazorPagesAJAX.Interfaces
{
    public interface ICarService
    {
        // Interface for getting and returning a list of cars
        List<Car> GetAll();
    }

    // The class can use the interface by appending ": I<name>"
    public class CarService : ICarService
    {
        // The GetALL() method has some data entered for testing...
        public List<Car> GetAll()
        {
            List<Car> cars = new List<Car> {
                new Car { Id = 1, Make = "Audi", Model = "R8", Year = 2014, Doors = 2, Colour = "Red", Price = 79995 },
                new Car { Id = 2, Make = "Aston Martin", Model = "Rapide", Year = 2010, Doors = 2, Colour = "Black", Price = 54995 },
                new Car { Id = 3, Make = "Porsche", Model = " 911 991", Year = 2016, Doors = 2, Colour = "White", Price = 155000 },
                new Car { Id = 4, Make = "Mercedes-Benz", Model = "GLE 63S", Year = 2017, Doors = 5, Colour = "Blue", Price = 83995 },
                new Car { Id = 5, Make = "BMW", Model = "X6 M", Year = 2016, Doors = 5, Colour = "Silver", Price = 62995 },
            };

            return cars;
        }
    }
}

AJAX Partial Page _CarPartial.cshtml:

<!-- The @inject might be the problem???  --->
@inject Interfaces.CarService carsList

<table class="table table-striped">
    <!-- carsList.GetAll() is the GetAll() list in ICarService interface-->
    @foreach (var car in carsList.GetAll())
    {
        <tr>
            <td>@car.Model</td>
            <td>@car.Make</td>
            <td>@car.Year</td>
            <td>[email protected]</td>
        </tr>
    }
</table>
<p>AJAX Updated at -  @DateTime.Now.</p>
question from:https://stackoverflow.com/questions/65546441/ajax-request-in-asp-net-core-3-1-razorpages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need inject interface ICarService instead of inheritance class CarService in _CarPartial.cshtml:

@inject ICarService carsList

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...