0

I decided to learn ASP.NET Core and I started by build a web page from scratch using the template ASP.NET Core Web API. I created a folder called Pages in my project where I added a razor page called Index.cshtml, in that razor page I have a form that lets a client enter a name and a query into text fields. I then added a new folder called Controllers to this project and added a file called FormController which has a method that is supposed to handle the data entered into the form by the user. I then gave the two input fields the same names as the parameter names in the method that should handle them in the FormController file but when I submit the form, the error HTTP 400 This page is not working now. My form uses the post method to send values to the controller, here is the HTML markup for the form that I am using to capture input from the user.

  <form onsubmit="return false;" method="post" asp-route="Form" asp-controller="FormController"  asp-action="GetAction" id="form">
    <div class="form-group">
       <label for="name">Name</label>
       <input type="text" name="name" class="form-control" id="name" placeholder="Enter your name" asp-for="Name">
    </div>
    <div class="form-group">
       <label for="query">Query</label>
       <textarea class="form-control" name="query" id="query" style="margin-top:20px" rows="5" placeholder="Enter your query" asp-for="Description"></textarea>
    </div> 
</form>

The controller that is supposed to be receiving these values from the form looks like this.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ASPLearner.Controllers
{
    [Route("api/[controller]",Name = "Form")]
    [ApiController]
    public class FormController : ControllerBase
    {
        //indicate to the method that we only need http post
        [HttpPost]
        public IActionResult GetAction(string name, string query)
        {
           
            // Redirect to a success page or return a response
            return RedirectToAction("Success");
        }
    }
}

I have also added support for MVC and mapped the controllers in my Startup C# code as shown below.

using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
//configure the services before calling the builder.build
IServiceCollection services = builder.Services;
//add controllers with views
services.AddControllersWithViews(); 
services.AddMvc();  
//add all the razor pages
services.AddRazorPages();
var app = builder.Build();
//alow static styling files to be loaded from wwwroot
app.UseStaticFiles();  
//add https redirection
app.UseHttpsRedirection();  
//add routing for the razor pages
app.UseRouting();
app.MapRazorPages();
app.MapFallbackToPage("/Index");
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
app.UseAuthorization(); 
app.Run();

The form shows up in a modal but when I fill random values and hit send, the page shown in the screenshot is displayed, help me get rid of the error so the values are successfully posted to the controller.

before enter image description here

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Son of Man
  • 1,213
  • 2
  • 7
  • 27

1 Answers1

1
  1. I don't think you could send the request with onsubmit="return false;"

  2. asp-route="Form" asp-controller="FormController" asp-action="GetAction" would result confliction

    asp-route="Form

would attach the parttern /api/[controller] name of Form to the action attribute of form (html element)

asp-controller="FormController"  asp-action="GetAction"

would attach /FormController/GetAction to action attribute

You should remove asp-controller="FormController" asp-action="GetAction",

3,If your controller is attached with [ApiController] attribute,it would bind

data from request body instead of request form,and when failed model validation,it would return 400 directly,you have to add [FromForm] attribute

You could check this document related,try modify as below

public IActionResult GetAction([FromForm]string name, [FromForm]string query)
        {

            // Redirect to a success page or return a response
            .....
        }

Codes in View:

<form  method="post" asp-route="Form" id="form">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name" class="form-control" id="name" placeholder="Enter your name" asp-for="Name">
    </div>
    <div class="form-group">
        <label for="query">Query</label>
        <textarea class="form-control" name="query" id="query" style="margin-top:20px" rows="5" placeholder="Enter your query" asp-for="Description"></textarea>
    </div>
    <div class="form-group">
        <input type="submit" value="Submit"/>
    </div>
</form>

Result:

enter image description here

Tried with modal as you expected:

    <div id="dialog" class="modal" tabindex="-1">
    <div class="modal-dialog modal-xl">
    <div class="modal-content">
        <form method="post" asp-route="Form" id="form">
            <div class="modal-header">
                <label for="name">Name</label>
                <input type="text" name="name" class="form-control" id="name" placeholder="Enter your name" asp-for="Name">
            </div>
            <div class="modal-body d-grid gap-3">
                <label for="query">Query</label>
                <textarea class="form-control" name="query" id="query" style="margin-top:20px" rows="5" placeholder="Enter your query" asp-for="Description"></textarea>
            </div>
            <div class="modal-footer">
                <input type="submit" value="Submit" />
            </div>
        </form>
    </div>
    </div>
    
</div>

<button id="opendialog">Open Dialog</button>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $(function () {
      
        $("#opendialog").click(function () {
            $("#dialog").modal('show')
        });
    });
</script>

Result: enter image description here

It doesn't matter,please show the codes related with sending request and press F12,select NetWork and check the request you've sent

enter image description here

Program.cs:

.....
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();
app.MapRazorPages();

app.MapFallbackToPage("/Index");

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

app.Run();
Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • Thanks let me try and update you if I get any results – Son of Man Jun 21 '23 at 04:48
  • Can you try with the form inside a modal because it's still not working on my end. – Son of Man Jun 21 '23 at 05:18
  • I am submitting the form with Javascript, the onsubmit ="return false" is for preventing the default behavior so I validate user input – Son of Man Jun 21 '23 at 05:20
  • I've updated my answer,in fact,it doesn't matter,please show the codes related with sending request and check the request you've sent – Ruikai Feng Jun 21 '23 at 06:07
  • Could it be a Model Validation Error as the Index.cshtml doesn't have a Model class file behind it such as Index.cshtml.cs – Son of Man Jun 21 '23 at 06:34
  • Index.cshtml.cs(Page Model) is for Razor Page ,not for MVC – Ruikai Feng Jun 21 '23 at 06:38
  • Let me try with MVC and see whether I will get something useful then – Son of Man Jun 21 '23 at 06:39
  • In fact,you could try remove [ApiController] and debug,then you could get into the controller and observe httpcontext.request.form/body/header to check the request you received as well – Ruikai Feng Jun 21 '23 at 06:44
  • I think the issue is mainly related with how you sent the request – Ruikai Feng Jun 21 '23 at 06:45
  • Okay let me do that then – Son of Man Jun 21 '23 at 08:14
  • In the second screenshot, the URL reads /api/Form, is API a folder in your project? Where is your Form Controller file? – Son of Man Jun 21 '23 at 08:42
  • No,it just a controller in Controllers folder,[Route("api/[controller]"] would override the default route parttern you registed in Program.cs – Ruikai Feng Jun 21 '23 at 08:53
  • Can I see your Program.cs startup code, maybe am not calling app.MapControllers or something – Son of Man Jun 21 '23 at 08:54
  • Never mind it worked – Son of Man Jun 21 '23 at 08:55
  • But it didn't work with your style, in the gif I saw your asp-route tagged to "api/Form" which also confused me – Son of Man Jun 21 '23 at 08:56
  • i've updated,in fact,I tried followed your settings to reproduce.... – Ruikai Feng Jun 21 '23 at 09:06
  • I have defined a Model class with getters and setters for the Name and Query, how do I create a database migration and create a new entry in a table every time user submits a request – Son of Man Jun 21 '23 at 09:34
  • Now it's okay to prevent on default and then use Javascript to validate user input and then submit when everything is okay – Son of Man Jun 21 '23 at 09:36
  • You could follow this document:https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-6.0&tabs=visual-studio – Ruikai Feng Jun 21 '23 at 09:36
  • https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio – Ruikai Feng Jun 21 '23 at 09:38
  • Whats the difference between ASP. NET and ASP.NET Core? Thanks – Son of Man Jun 22 '23 at 08:12
  • https://stackoverflow.com/questions/37684508/difference-between-asp-net-core-net-core-and-asp-net-core-net-framework you could check this issue related – Ruikai Feng Jun 22 '23 at 08:21
  • Is it possible to show the errors defined in the model page in red inside a Modal? – Son of Man Jun 22 '23 at 08:23
  • check the html element rendered for validation message and add css codes for your requirement – Ruikai Feng Jun 22 '23 at 08:37
  • I don't think you understood me, when I submit the form then the modal will close, I would like to prevent the modal from closing so that the validation rules I have defined in the Model Page index.cshtml.cs are displayed in the span tags – Son of Man Jun 22 '23 at 10:46
  • https://stackoverflow.com/questions/76328203/asp-net-core-7-mvc-model-errors-on-modal-popup/76328749#76328749 you could try follow this case – Ruikai Feng Jun 23 '23 at 01:11
  • You also forgot to mention that we both the Route Name for the controller and the "api/controller" needs to be unique for each controller. If you need another controller class foraube deleting records from a table then perhaps it needs to be "api/controller1" and "Delete" as the route name. Is this correct? – Son of Man Jun 25 '23 at 18:46