表单 Http POST 不起作用,只有 Get 在 asp 核心 mvc 中起作用

the form Http POST doesn't work, only Get work in asp core mvc

我有一个应该通过 POST 请求传递数据的表单,但是正在使用 GET 请求而不传递数据并进行 asp 核心的模型绑定,所以方法 Registrationp 如果属性 [HttpPost] 就位,则永远不会到达 ;( 。 我尝试了很多方法来解决这个问题,但 none 如果它们有效,即使其他形式 post 数据并成功绑定模型

HTML:

@model Student_Training.Models.File; 

<form method="post" asp-controller="Students" asp-action="Registrationp" enctype="multipart/form-data">
    <label asp-for="FileRep" class="col-sm-2 col-form-label"></label>
    <div class="col-sm-10">
        <div class="custom-file">
            <input type="file" asp-for="FileRep" name="img" accept="image/*" class="form-control custom-file-input" />
            <label class="custom-file-label"> Upload...</label>
        </div>
    </div>
    <div class="form-group">
        <button id="Button" type="submit" name="submit" formmethod="post" class="btn btn-secondary btn-sm">
            <a asp-action="Registrationp"> Save </a>
        </button>
    </div>
</form>

控制器POST方法:

[HttpPost]
        public async Task<IActionResult> Registrationp([Bind("FileId, FileName, OwnerId, FileRep")] Student_Training.Models.File imgFileModel, IFormFile img, int? id)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);
            var userEmail = user.Email;
            Student Student = _context.Student.FirstOrDefaultAsync(x => x.Email == userEmail).Result;
            // StudentId
            id = Student.StudentId;

            // Save img to wwwroot/img folder
            string wwwRootPath = _hostEnvironment.WebRootPath;
            Student_Training.Models.File myFile = new Student_Training.Models.File();
            string fileName = Path.GetFileNameWithoutExtension(imgFileModel.FileRep.FileName);
            string extention = Path.GetExtension(imgFileModel.FileRep.FileName);
            imgFileModel.FileName = fileName = fileName + DateTime.Now.ToString("yymmss") + extention;
            string path = Path.Combine(wwwRootPath + "/img/", fileName);
            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                await imgFileModel.FileRep.CopyToAsync(fileStream);
            }
            // insert recorod to Db
            _context.Add(imgFileModel);
            await _context.SaveChangesAsync();

            return View();
        }

事实上,您使用的是锚标记来提交表单,而不是提交按钮。锚标记总是生成 GET 请求。所以只需将其从您的代码中删除:

<button id="submitButton" type="submit"  class="btn btn-secondary btn-sm">Save</button>