Hi everyone,
Do you know if there is a way to send a ViewModel through a RedirectToAction method ?
Indeed I'd like to display the ViewModel errors when the ModelState is not valid inside the CreateBook method :
BookViewModel :
using System.ComponentModel.DataAnnotations;
namespace Blog.ViewModels.Home
{
public class BookViewModel
{
[Required(ErrorMessage = "Please specify a name")]
[Display(Name = "Name : ")]
public string Name { get; set; }
[Required(ErrorMessage = "Please specify a price")]
[Display(Name = "Price : ")]
public int Price { get; set; }
}
}
Index.cshtml :
@model Blog.ViewModels.Home.BookViewModel
@{
ViewData["Title"] = "Blog";
Layout = "_Layout";
}
@section page_content{
<p>Hello World form Blog !</p>
<form novalidate asp-controller="Home" asp-action="CreateBook" method="post">
<label asp-for="@Model.Name"></label>
<input asp-for="@Model.Name">
<span asp-validation-for="@Model.Name"></span>
<label asp-for="@Model.Price"></label>
<input asp-for="@Model.Price">
<span asp-validation-for="@Model.Price"></span>
<input type="submit" value="Continuer">
</form>
}
HomeController :
using Blog.ViewModels.Home;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var bookViewModel = new BookViewModel();
return View(bookViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateBook(BookViewModel bookViewModel)
{
if(!ModelState.IsValid)
// When the ModelState is not valid, I'd like to redirect the user
// to the "Index" Action with the bookViewModel to display form errors
return RedirectToAction("Index", "Home", bookViewModel);
// Will save the data to the DB after if ModelState is valid
return RedirectToAction("Index", "Home");
}
}
}
Thanks in advance for your help