Hi there,
I have a Controller called ProductController. The Controller code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Services.Abstract;
using Web.Models;
using Ninject;
using Services.Entities;
namespace Web.Controllers
{
public class ProductController : Controller
{
IProductRepository productRepository;
public ProductController(IProductRepository products)
{
productRepository = products;
}
[HttpGet]
public ActionResult Create() {
Product p = new Product {
Id = 5
};
string theTitle = "The Title";
var viewModel = new ProductViewModel {
Product = p,
TheTitle = theTitle
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ProductViewModel pvm) {
if (ModelState.IsValid) {
int result = productRepository.SaveProduct(pvm.Product);
return Content(result.ToString());
}
else {
return View(pvm);
}
}
}
}
I am using the ViewModel pattern to send various bits of information to the View. For example, I am sending a Product with a default Id set to 5, and I am also setting a title property [Aside: this is not production code - just test data :-)]
All good so far. When /Product/Create is called for the first time, my Title property is displayed on the view, and the Product Id defaults to 5. However, when I post the form, only the Product information is retained. If the ModelState is not Valid, I display the View to the user again. However, this time around, the Title does not display (it is set to null). The product does display as expected though.
If possible I would like to send the original Title back to the view when the ModelState is not valid. Is there any way to do this without using Session, ViewData, and TempData?
Regards, and thanks in advance