问题
I am using asp.net core razor engine. Is there a way to get an anchor tag to access my Create method like a form tag does. I tested my code using a form tag and it works, is there a way to have the anchor tag do the same?
Here is my code
<div id = "menu">
@model ecommerce.Models.Users
<a asp-controller="Product" asp-action="Create" method="post" role="form">Test</a> // This is the anchor tag that I want to have the same behavior as the form tag below
<form asp-controller="Product" asp-action="Create" method="post" role="form">
<button type="submit">Add to Quotes</button>
</form>
</div>
回答1:
The problem you are facing is that an anchor tag will create a GET
request and a form post will be a POST
request. That's why your anchor will not hit the same create method as your form post.
If you just want to redirect the user after the form post then just do a normal form post and redirect them at the end of the create method. This is a very common thing.
If you really want the anchor to point to a create method then create a second version of the method which is a GET
and point the anchor tag there.
回答2:
@nurdyguy's answer explains well why it does not work.
Here is how you can get anchor element to do post request:
<form asp-controller="Account" asp-action="LogOff" method="post">
<a onclick="this.parentElement.submit()">Log off</a>
or using a jQuery:
<a onclick="$(this).closest('form').submit()">Log off</a>
</form>
来源:https://stackoverflow.com/questions/41619122/asp-net-core-using-an-anchor-tag-to-work-like-a-form