locked
dynamically building the action URL for our post form is not working RRS feed

  • Question

  • User-540818677 posted

    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/

    Friday, July 10, 2020 1:04 AM

All replies

  • User-2054057000 posted

    The below code is very confusion and probably building the action incorrectly:

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

    You need to replace it. What you can do is create your action in string type in the Controller and then return this string in Viewbag to the View. In your view you can then simply assign this form's action property to the Viewbag's value.

    Friday, July 10, 2020 5:47 AM
  • User711641945 posted

    Hi johnjohn123123,

    Because you have a `ValidateAntiForgeryToken` attribute,you need to add `@Html.AntiForgeryToken()` in your razor view:

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

    Best Regards,

    Rena

    Friday, July 10, 2020 7:37 AM