简体   繁体   中英

My Post form is not reaching the action method inside my asp.net mvc core web application

I am working on an asp.net MVC core web application, and i have the following routing rules:-

app.UseEndpoints(endpoints => {

                endpoints.MapControllerRoute(
                    name: "IP",
                    pattern: "IP/{controller=Home}/{action=Index}/{id?}");
            });
            app.UseEndpoints(endpoints => {

                endpoints.MapControllerRoute(
                    name: "Info",
                    pattern: "Info/{controller=Home}/{action=Index}/{id?}");
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

then inside my create form i define the following to use different url when posting back the form depending on the current url:-

<form method="post" action="@(!Context.Request.Path.Value.ToString().ToLower().Contains("/info") ? "/IP/submissions/create/": "/info/submissions/create/")" >

and here is my post action method:-

 [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Submission,SubmissionQuestionSubmission")] SubmissionCreate sc )
        {

but currently when i post back the form the action method will not be called... any idea? and the browser console will raise this error:-

HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
POST - https://localhost:44363/info/Submissions/Create/

It's a "Bad Request" because you aren't using the form tag helper . Which should build the action url for you and add an anti forgery token.

However, your routes and controller actions should have a 1-1 mapping. Right now you have 3 different routes to the same actions. How are those actions supposed to know which route was used and therefore what action to take? Are you planning on checking the raw url in each action?

Are you attempting to split your controllers into areas ? In which case adding the asp-controller , asp-action , asp-route-... attributes will cause the form tag helper to build the right url for you.

Or would you prefer to add an extra argument to each action, indicating which url was used. Which you could then add to your model so your view can provide it as a route parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM