Reputation: 77
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.
Upvotes: 0
Views: 547
Reputation: 18209
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:
Upvotes: 0
Reputation: 155513
asp-action...
tag-helpers are for use on <a>
and <form>
elements, not <button>
.type="button"
on your <button>
.
type="button"
means that the button, when clicked, does nothing.<button>
to type="submit"
to submit the parent <form>
element.asp-action=""
and asp-controller=""
helpers to your <form>
.Upvotes: 2