微软教程中的 http 405 错误 - asp.net mvc

http 405 error in microsoft totorial - asp.net mvc

“创建”部分让我很头疼

StudentsController.cs

using ContosoUniversity.Data;
using ContosoUniversity.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ContosoUniversity.Controllers
{
    public class StudentsController : Controller
    {
        private readonly SchoolContext _context;

        public StudentsController(SchoolContext context)
        {
            _context = context;
        }
        public async Task<IActionResult> Index()
        {
            return View(await _context.Students.ToListAsync());
        }

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

            var student = await _context.Students
                .Include(s => s.Enrollments)
                    .ThenInclude(e => e.Course)
                .AsNoTracking()
                .FirstOrDefaultAsync(m => m.ID == id);

            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(student);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                    "Try again, and if the problem persists " +
                    "see your system administrator.");
            }
            return View(student);
        }


 


    }
}

Create.cshtml

@model ContosoUniversity.Models.Student

@{
    ViewData["Title"] = "Create";
}

<h1>CreateView</h1>

<h4>Student</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label"></label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FirstMidName" class="control-label"></label>
                <input asp-for="FirstMidName" class="form-control" />
                <span asp-validation-for="FirstMidName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EnrollmentDate" class="control-label"></label>
                <input asp-for="EnrollmentDate" class="form-control" />
                <span asp-validation-for="EnrollmentDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

如果我删除“[HttpPost]”,我的模型会立即更新并提交空数据,returns 到索引页面

link实际教程:

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-5.0#update-the-create-page

谢谢

由于操作具有 [ValidateAntiForgeryToken] 属性,您应该将其添加到视图中,并用 html 帮助程序

替换表单标签
@using (Html.BeginForm("Create", "Students", FormMethod.Post)) 
{
    @Html.AntiForgeryToken()
   <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 .... and so on

}

恕我直言,不要在您的 post 操作中使用任何绑定,这绝不是一个好主意

[HttpPost("~/students/create")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Student student)

您只需要将method="post"添加到<form></form>

<form asp-action="Create" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label"></label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FirstMidName" class="control-label"></label>
                <input asp-for="FirstMidName" class="form-control" />
                <span asp-validation-for="FirstMidName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EnrollmentDate" class="control-label"></label>
                <input asp-for="EnrollmentDate" class="form-control" />
                <span asp-validation-for="EnrollmentDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>

因此表单将包含一个名为 __RequestVerificationToken 的隐藏输入,其中包含 AntiForgeryToken.When 表单提交的值,令牌将传递给创建操作。

找到了一个解决方案...我需要另一种 HttpGet 方法,具有相同的名称(创建)...仍然不确定为什么,现在可以使用,没有 405 错误

如果有人有好的解释,请

这是我在控制器中添加的:

public IActionResult Create()
        {
            return View();
        }