Search code examples
asp.netasp.net-mvcasp.net-coreasp.net-core-mvchttp-post

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


I have a Form that should pass data through POST request, but GET request is being used without passing the data and do model binding of asp core, so buz of that the method Registrationp is never reach if the attribute [HttpPost] is in place ;( . I tried many ways to get over this problem but none if them worked, even though the other forms post the data and bind the model successfully

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>

Controller POST method:

[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();
        }

Solution

  • As a matter of fact you are using an ancor tag to submit your form, not a submit button. An ancor tag is always generates a GET request. So just remove it from your code:

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