Hi @Bruce (SqlWork.com) , thanks for your answer.
Well I bypassed this issue by using an HttpPost version of my Index method instead, that way I can return View with the ViewModel inside.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
Hi @Bruce (SqlWork.com) , thanks for your answer.
Well I bypassed this issue by using an HttpPost version of my Index method instead, that way I can return View with the ViewModel inside.
A redirect causes the browser to do a get. You can pass query string parameters, but there is a max length for a query string. In general is frowned upon to pass model data via a query string. Your best option is to store the model in persistent storage, and pass a key to the model data on the query string.