Reputation: 19
I'm learning ASP.NET CORE 6 with MS official website below: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Then I found a instruction said "There's no [HttpPost] overload of the Index method as you might expect. You don't need it, because the method isn't changing the state of the app, just filtering data." and I'm confused with it.
the following code is the sample from teaching page, a form tag without method atrribute, so I think it should be "post" as the default.
<form asp-action="index">
Search: <input type="text" name="searchText" />
<input type="submit" value="GO" class="btn btn-secondary" />
</form>
And the following action method without [HTTPXXX] attribute should be [HTTPGET] as the default, right?
// GET: Movies
public async Task<IActionResult> Index(string searchText)
{
if (!string.IsNullOrEmpty(searchText))
{
var result = _context.Movie.Where(m=>m.Title!.Contains(searchText));
return View(await result.ToListAsync());
}
return View(await _context.Movie.ToListAsync());
}
So the question is why I ask a request with POST method, but it still can lead to a GET action method?
Upvotes: 0
Views: 835
Reputation: 22495
And the following action method without [HTTPXXX] attribute should be [HTTPGET] as the default, right?
Well, if you don't define your from submit method attribute
by default it will authometically generate method type
as post
like this method="post"
. If you could inspect you can see as below:
So the question is why I ask a request with POST method, but it still can lead to a GET action method?
Yes you are right. In that case, either you have to define as method="get"
or you can define and controller and action together. Like this
<form asp-action="index" asp-controller="YourController">
Or
<form asp-action="index" method="get">
Note: In official document they used asp-controller="Movies"
however, you haven't use it in your code which created the issue.
Output:
Note: Using method attribute
method="get"
is more suitable to resolve your issue other than in browser compiler autometically generate post
by default.
Upvotes: 1
Reputation: 971
According to HTML specification default value for form.method attributge is 'get'. See https://www.w3.org/TR/html401/interact/forms.html#edef-FORM and https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/method. That's why it works with GET action, as if you specified <form asp-action="index" method="get">
Upvotes: 1