I am trying to learn ASP.NET Core v7 preview following along with BHRUGEN Patel's Youtube video
Controller:
public async Task<IActionResult> OnPost(Category category)
{
if (ModelState.IsValid)
{
await _db.Categories.AddAsync(category);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
return View("Index");
}
Output:
Debugging Stpes:
"How can I debug the model? Or look at how it is using the data annotations? "
- Check the inspect element on your UI code.
- Make sure
data-valmsg-for
andname
orid
attributes are matched properly.- See the below screen capture for details steps
Note:
Make sure you have
_ValidationScriptsPartial.cshtml
on yourshared
folder and it should contains following references:<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
Hope it would resolve your problem accordingly.You could refer to our official document
for more details here
CodePudding user response:
With the help of codementor.io, we figured out that when there is an error on the page and your server is catching the error, your ModelState is sent back to the client as Invalid. If you redirect to an action, you are destroying this cache. IN this case, redirecting to Create.cshtml cleared the session in memory. Just redirect to the Page, then you will see the server errors.
public async Task<IActionResult> OnPost()
{
if(Category.Name == Category.DisplayOrder.ToString())
{
ModelState.AddModelError("Category.Name", "Category name cannot be the same as category display order");
}
if (ModelState.IsValid)
{
await _db.Category.AddAsync(Category); //the BindProperties attribute above takes care of this--not having to pass category Category, just use a capital C to bind it to the Category model
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
else
//2022-05-19, Problems were occurring on the error messages returned and displayed (i.e., they were not) from the server.
//
//Resolved on codementor.io: When ModelState.Isvalid returns false,
//you do not need to redirect to Create.cshtml, ***because the state of the model will be lost, because model state is stored
//in memory cache, i.e. by session; rather you just return the page (ie return Page())
return Page(); <--return page, don't redirect to Create, or the action
}