.NET MVC按钮调用带参数控制器Action遇参数引用及404错误问题
Hey there, that 404 error is happening because of a small but critical mistake in your form's action attribute! Let's break down the issue and fix it right away.
The Root Cause
In ASP.NET Core (and most ASP.NET frameworks), when referencing controller actions in your form's action path, you don't include the "Controller" suffix in the controller name. Your current action points to HomeController/getTrialKey, but the correct path should reference just Home (the base name of your controller) followed by the action name.
Fixed Form Code
Here's the corrected version of your form with the proper action path:
<form action="/Home/getTrialKey" method="POST"> <label for="productKey">Product Key:</label> <input type="text" name="productKey" maxlength="22" value="xxx xxxxxxx xxxx xxxxx"><br><br> <input type="submit" value="Get Trial Key" class="btn btn-primary" /> </form>
Adding the leading / ensures the path is rooted to your application's base URL, avoiding any relative path issues if this view lives in a subfolder.
Even Better: Use ASP.NET Core Tag Helpers
To avoid hardcoding paths entirely (and prevent future typos), use the built-in form tag helpers. This will automatically generate the correct action URL based on your controller and action names:
<form asp-controller="Home" asp-action="getTrialKey" method="POST"> <label for="productKey">Product Key:</label> <input type="text" name="productKey" maxlength="22" value="xxx xxxxxxx xxxx xxxxx"><br><br> <input type="submit" value="Get Trial Key" class="btn btn-primary" /> </form>
Just make sure you've got tag helpers enabled in your view (usually via @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers in your _ViewImports.cshtml file).
Quick Double-Checks
- Confirm your controller class is named
HomeController(matches theasp-controller="Home"value) - Ensure your action method is decorated with
[HttpPost]and accepts astring productKeyparameter (which you already have set up correctly) - If you've added custom routing attributes to your controller or action, make sure they align with the path you're using
That should resolve the 404 error and let your form submit correctly to the action!
内容的提问来源于stack exchange,提问作者jefferson vaughn

