I am running same code on ASP.NET Core, the get request working well and it populate the view but when it comes to form submission it says bad request. I am not sure why it is happening. It is not totally hitting the OnPost
Method in code behind.
Here is my Razor page:
@page
@using Northwind.EntityModels
@model Northwind.Web.Pages.SupplierModel
@addTagHelper *, MicroSoft.AspNetCore.Mvc.TagHelpers
<div class="row">
<h1 class="display-2">Suppliers</h1>
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Company Name</th>
<th>Country</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
@if (Model.Suppliers is not null)
{
@foreach(Supplier s in Model.Suppliers)
{
<tr>
<td>@s.CompanyName</td>
<td>@s.Country</td>
<td>@s.Phone</td>
</tr>
}
}
</tbody>
</table>
</div>
<div class="row">
<p>Enter details for a new Supplier.</p>
<form method="post" asp-page="/Supplier" novalidate>
<div>
<input asp-for="Supplier.CompanyName" placeholder="company name"/>
</div>
<div>
<input asp-for="Supplier.Country" placeholder="country name" />
</div>
<div>
<input asp-for="Supplier.Phone" placeholder="Phone name" />
</div>
<input type="submit"/>
</form>
</div>
@{
}
And this is my code behind, any explanation will be welcome as I am learning it. I asked so much to chatgpt but not able to get an answer.
using Microsoft.AspNetCore.Mvc;// To use [BindProperty], IActionResult.
using Microsoft.AspNetCore.Mvc.RazorPages;
using Northwind.EntityModels;
namespace Northwind.Web.Pages
{
public class SupplierModel : PageModel
{
private NorthwindContext _dbContext;
public IEnumerable<Supplier>? Suppliers { get; set; }
private readonly ILogger<SupplierModel> _logger;
// add a property to store a single supplier
[BindProperty]
public Supplier? Supplier { get; set; }
// OnPost that adds the supplier to the Suppliers table
public IActionResult OnPost()
{
_logger.LogInformation("Onpost method excuted at {time}", DateTime.Now);
// validation rule checking according to entity model
// like required, string length
if (Supplier is not null && ModelState.IsValid)
{
// Log company name
_logger.LogInformation("Valid Supplier data received: {companyName}", Supplier.CompanyName);
WriteLine("is valid supplier");
_dbContext.Suppliers.Add(Supplier);
_dbContext.SaveChanges();
return RedirectToPage("/Supplier");
}
else
{
// Log a warning
_logger.LogWarning("Invalid supplier data or ModelState is not valid");
WriteLine("not valid supplier");
// Return the original page
return Page();
}
}
public SupplierModel(NorthwindContext db, ILogger<SupplierModel> logger)
{
_dbContext = db;
_logger = logger;
}
public void OnGet()
{
ViewData["Title"] = "Northwind B2B -Suppliers";
Suppliers = _dbContext.Suppliers
.OrderBy(c => c.Country)
.ThenBy(c => c.CompanyName);
}
}
}
My folder strcutre:
3