为什么我的表单不向我的控制器传递参数?

Why my form does not pass parameters to my controller?

我正在尝试将用户在表单中输入的值传递给 ASP.NET MVC 控制器以处理到数据库上下文。我不知道为什么表单中的值没有传递给具有相同参数名称的控制器方法,因为当我尝试提交表单时,它什么也不做。请帮助我正确地执行此操作以将条目从表单传递到控制器。

这是我的控制器代码:

using Cars.Models;
using Microsoft.AspNetCore.Mvc;

namespace Cars.Controllers
{
    public class CarController : Controller
    {
        //declare the reference to database
        CarsContext _context ;

        public CarController()
        {
            _context = new CarsContext();
        }

        [HttpPost]
        //this method is supposed to receive the form values
        //and insert into the database
        public void GetProperties(string make, string model, string year, string nop)
        {
            // create a new car object
            Car car = new Car()
            {
                Make = make,
                Model = model,
                Year = Int32.Parse(year),
                NoPassengers = Int32.Parse(nop)
            };

            // create a new database context
            _context.Add(car);

            // save changes
            _context.SaveChanges();
        }

        // method to get all the cars
        public List<Car> GetAllCars()
        {
            // create a new database context
            return _context.Car.ToList();
        }

        // method to get a car by id
        public Car? GetById(int? id)
        {
            return _context.Car.FirstOrDefault(c => c.Id == id);
        }

        // method to check if a car exists
        public bool Exists(Car obj)
        {
            return _context.Car.Where(c => c.Id == obj.Id).Any();
        }

        // return cars whose passenger seats is three or less
        public List<Car> ThreePassengers()
        {
            return _context.Car.Where(c => c.NoPassengers <= 3).ToList();  
        }
    }
}

这是我的 index.cshtml 视图,其中包含我需要通过参数传递给控制器​​的值

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Car Property Editor</h1>
   <p>Fill out the details of the car in the form below </p>
   <br/>
   <br/>
   @using (Html.BeginForm("GetProperties", "CarController"))
   {
   <table class="table">
     <thead>
         <tr>
             <td>Make</td>
             <td>Model</td>
             <td>Year Manufactured</td>
             <td>Number of Passengers</td>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>@Html.TextBox("make")</td>
               <td>@Html.TextBox("model")</td>
                 <td>@Html.TextBox("year")</td>
                   <td>@Html.TextBox("nop")</td>

         </tr>
     </tbody>
     <br/>

   </table>
    <center><input class="btn" type="submit" value="Insert"asp-action="myfunction()" style="background:blue;color:#111"></center>
   }
   <button class="btn">Get All Cars</button>
   <button class="btn">Get Car  by Id</button>
   <button class="btn">Get Car with three passenger seats</button>
   <button class="btn">Sort Cars by year manufactured</button>
</div>
  1. 您需要知道您在项目中将 ASP.NET Core MVC 与 ASP.NET Core Razor Pages 混合使用。您可以看到您的前端使用 Razor Pages 中使用的 @page ,但您的后端代码是 MVC 中使用的 public class CarController : Controller

  2. 你使用@using (Html.BeginForm("GetProperties", "CarController")),第二个参数匹配控制器名称,只需使用Car而不是CarController

  3. @using (Html.BeginForm("GetProperties", "CarController")) 将生成如下 html 代码,因此无需添加额外的 asp-action="ActionName".

    <form action="/Car/GetProperties" method="post">   
        //other html code....
    </form>
    

最重要的是,如下更改您的前端代码:

@page
@model IndexModel
<div class="text-center">
    <h1 class="display-4">Car Property Editor</h1>
   <p>Fill out the details of the car in the form below </p>
   <br/>
   <br/>
   @using (Html.BeginForm("GetProperties", "Car"))
   {
   <table class="table">
     <thead>
         <tr>
             <td>Make</td>
             <td>Model</td>
             <td>Year Manufactured</td>
             <td>Number of Passengers</td>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>@Html.TextBox("make")</td>
               <td>@Html.TextBox("model")</td>
                 <td>@Html.TextBox("year")</td>
                   <td>@Html.TextBox("nop")</td>

         </tr>
     </tbody>
     <br/>

   </table>
    <center><input class="btn" type="submit" value="Insert" style="background:blue;color:#111"></center>
   }
   <button class="btn">Get All Cars</button>
   <button class="btn">Get Car  by Id</button>
   <button class="btn">Get Car with three passenger seats</button>
   <button class="btn">Sort Cars by year manufactured</button>
</div>

务必在 Startup.cs:

中添加 MVC 路由模板
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        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)
    {  
        //other middlewares.....
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

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