从 asp.net mvc 核心中的视图调用控制器操作

Call controller action from view in asp.net mvc core

我尝试从 asp.net 核心中的视图调用控制器方法。 我的项目中有两个不同的控制器。一个 Homecontroller 和一个用于我的 Model Pupil 的控制器。 从 layout.cshtm 中的导航中,我尝试调用我的 Pupilcontroller 的索引方法:

<a asp-action="Index" asp-controller="Pupil">Home</a>

我也试过@Html.Action("Pupil","Index","Pupil") 但没有任何效果。

这是我的控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using svkcore.Models;

namespace svkcore.Controllers
{
    public class PupilController : Controller
    {
        private readonly SchuleContext _context;

        public PupilController(SchuleContext context)
        {
            _context = context;
        }

        // GET: Pupil
        public async Task<IActionResult> Index()
        {
            var schuleContext = _context.Pupils.Include(s => s.Ansprechpartner).Include(s => s.Fach);
            return View(await schuleContext.ToListAsync());
        }

        // GET: Pupil/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var pupil= await _context.Pupils
                .Include(s => s.Ansprechpartner)
                .Include(s => s.Fach)
                .FirstOrDefaultAsync(m => m.Idschueler == id);
            if (pupil== null)
            {
                return NotFound();
            }

            return View(pupil);
        }

        // GET: Pupil/Create
        public IActionResult Create()
        {
            ViewData["AnsprechpartnerId"] = new SelectList(_context.Ansprechpartners, "Idansprechpartner", "Adresse");
            ViewData["FachId"] = new SelectList(_context.Faches, "Idfach", "Fach1");
            return View();
        }

        // POST: Pupil/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Idschueler,Vorname,Nachname,AnsprechpartnerId,FachId,Klasse,Telefonnummer,Geburtstag")] Schueler schueler)
        {
            if (ModelState.IsValid)
            {
                _context.Add(pupil);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["AnsprechpartnerId"] = new SelectList(_context.Ansprechpartners, "Idansprechpartner", "Adresse", pupil.AnsprechpartnerId);
            ViewData["FachId"] = new SelectList(_context.Faches, "Idfach", "Fach1", schueler.FachId);
            return View(pupil);
        }

        // GET: Schueler/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var schueler = await _context.Pupils.FindAsync(id);
            if (schueler == null)
            {
                return NotFound();
            }
            ViewData["AnsprechpartnerId"] = new SelectList(_context.Ansprechpartners, "Idansprechpartner", "Adresse", pupil.AnsprechpartnerId);
            ViewData["FachId"] = new SelectList(_context.Faches, "Idfach", "Fach1", schueler.FachId);
            return View(pupil);
        }

        // POST: Pupil/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Idschueler,Vorname,Nachname,AnsprechpartnerId,FachId,Klasse,Telefonnummer,Geburtstag")] Pupil pupil)
        {
            if (id != schueler.Idpupil)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(pupil);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SchuelerExists(pupil.IdPupil))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["AnsprechpartnerId"] = new SelectList(_context.Ansprechpartners, "Idansprechpartner", "Adresse", pupil.AnsprechpartnerId);
            ViewData["FachId"] = new SelectList(_context.Faches, "Idfach", "Fach1", schueler.FachId);
            return View(pupil);
        }

        // GET: Schueler/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var schueler = await _context.Pupils
                .Include(s => s.Ansprechpartner)
                .Include(s => s.Fach)
                .FirstOrDefaultAsync(m => m.IdPupil == id);
            if (Pupil== null)
            {
                return NotFound();
            }

            return View(Pupil);
        }

        // POST: Pupil/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var schueler = await _context.Pupils.FindAsync(id);
            _context.Schuelers.Remove(pupil);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool PupilExists(int id)
        {
            return _context.Schuelers.Any(e => e.Idschueler == id);
        }
    }
}

the Routing in the Startup.cs:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                
                endpoints.MapRazorPages();
            });

我总是得到这个答案: InvalidOperationException:尝试激活 'svkcore.Controllers.SchuelerController'.

时无法解析类型 'svkcore.Models.SchuleContext' 的服务

有人可以提供任何建议,如何从视图中的 link 调用不同的控制器? 提前谢谢了! 彼得

#Startup-Class

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using svkcore.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace svkcore
{
    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.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddControllersWithViews();
        }

        // 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();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Home/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.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                
                endpoints.MapRazorPages();
            });
        }
    }
}

A​​pplicationDbContext更改为SchuleContext

services.AddDbContext<SchuleContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

但是,如果您还想注入 A​​pplicationDbContext,请进行以下配置。

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

services.AddDbContext<SchuleContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));