I have a button and I trigger an action in my controller via the button. The button has tag helpers for the controller, route id, and action (see below):
(Line-breaks inserted for readability)
<div class="input-group-append">
<button
class="btn btn-outline-secondary"
type="button"
asp-controller="Home"
asp-route-Id="@Model.Project.Id"
asp-action="UploadDocument"
id="uploadDocument"
>
Upload
</button>
</div>
Here is the IActionResult
in the controller:
//POST - Upload document
[HttpPost("~/Home/UploadDocument")]
public IActionResult UploadDocument(int id, IFormFile files)
{
//Get and upload file
if (files != null)
{
if (files.Length > 0)
{
//Getting FileName
var fileName = Path.GetFileName(files.FileName);
//Getting file Extension
var fileExtension = Path.GetExtension(fileName);
// concatenating FileName FileExtension
//var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);
var objfiles = new Document()
{
Id = 0,
Name = fileName,
FileType = fileExtension,
ProjectId = id
};
using (var target = new MemoryStream())
{
files.CopyTo(target);
objfiles.DataFiles = target.ToArray();
}
_db.Files.Add(objfiles);
}
}
_db.SaveChanges();
return View(Update(id));
}
I put a breakpoint on the first line of code in UploadDocment
and clicked the button. Nothing happened. The breakpoint never got hit. I'm not sure why this isn't working. I have:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
... in my _ViewImports.cshtml
file and the tag helpers work on other buttons.
CodePudding user response:
- The
asp-action...
tag-helpers are for use on<a>
and<form>
elements, not<button>
. - Additionally, another part of the problem is the
type="button"
on your<button>
.type="button"
means that the button, when clicked, does nothing.
- So, to correct things:
- Change your
<button>
totype="submit"
to submit the parent<form>
element. - And move the
asp-action=""
andasp-controller=""
helpers to your<form>
.
- Change your
CodePudding user response:
You need to put <button>
inside <form method="post"></form>
.
<form method="post">
<button class="btn btn-outline-secondary"
asp-controller="Home"
asp-route-Id="@Model.Project.Id"
asp-action="UploadDocument"
id="uploadDocument">Upload</button>
</form>
result: