I am using ASP.net core razor engine. I am trying to display my error in my html. Not sure how to go about fixing my code. How do I display the errors from
ModelState.Values
in my cshtml page?
Here is my controller
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using quotingDojo.Models;
namespace quotingDojo.Controllers
{
public class HomeController : Controller
{
// GET: /Home/
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("quotes")]
public IActionResult Quotes(string Name, string Quote)
{
Home NewHome = new Home
{
Name = Name,
Quote = Quote
};
if(TryValidateModel(NewHome) == false) {
ViewBag.errors = ModelState.Values;
System.Console.WriteLine("??????????????");
System.Console.WriteLine(ModelState.ErrorCount);
System.Console.WriteLine("??????????????");
}
return RedirectToAction("Index");
}
}
}
ModelState.ErrorCount
prints out the correct number of errors.
Here is my model
using System.ComponentModel.DataAnnotations;
namespace quotingDojo.Models
{
public class Home
{
[Required(ErrorMessage ="Please enter your name")]
[Display(Name="*username")]
[DataType(DataType.Text)]
[MinLength(3)]
public string Name {get; set;}
[Required]
[MinLength(5)]
public string Quote{get; set;}
}
}
Here is my cshtml page
<div id="wrapper">
<h1>Welcome to the Quoting Dojo</h1>
<form action="quotes" method="post">
<p>
<label>Your Name</label>
<input type="text" name="Name"/>
</p>
<p>
<label>Your Quote</label>
<textarea name="Quote" id="quote" cols="30" rows="10"></textarea>
</p>
<input type="submit" name="submit" value="Add my quote!"/>
<form action="quotes" method="get">
<input type="submit" name="submit" value="Skip to quotes!"/>
</form>
</form>
</div>
<div>
<p> Test</p>
@{
if(ViewBag.errors != null)
{
foreach(var error in ViewBag.errors)
{
//If there are any errors for a field...
if(@error.errors.Count > 0)
{
// We show the first error for that field
<p>@error.errors[0].ErrorMessage</p>
}
}
}
}
</div>
I am using Visual Studio Code so anything build into regular Visual Studio I do not have access build in.