I'm developing a web application using MVC 4 and Entity Framework. I'm using a ViewModel which represents a Product to create/edit/delete. I have created a validation class which check the entries and displays an error message when it is necessary.
Since I'm using a ViewModel, unfortunately the error messages are not displayed anymore? How should I proceed?
Here's my ViewModel :
public class ProductViewModel
{
public Product Product { get; set; }
public ProductType ProductType { get; set; }
public List<SelectListItem> ProductCompanies { get; set; }
}
Here's my action (create, for example) :
[HttpPost]
public ActionResult Create(ProductViewModel pvm)
{
pvm.ProductCompanies = db.ProductCompanies.ToList().Select(s => new SelectListItem
{
Text = s.Name,
Value = s.Id_ProductCompany.ToString()
}).ToList();
ViewBag.Id_ProductCompany = new SelectList(db.ProductCompanies, "Id_ProductCompany", "Name", pvm.ProductType.Id_ProductCompany);
if (ModelState.IsValid)
{
ModelStateDictionary errors = Validator.isValid(pvm.ProductType);
if (errors.Count > 0)
{
ModelState.Merge(errors);
return View(pvm);
}
Product product = new Product
{
PurchaseDate = pvm.Product.PurchaseDate,
SerialNumber = pvm.Product.SerialNumber,
Id_ProductType = pvm.ProductType.Id_ProductType
};
ProductType productType = new ProductType
{
Model = pvm.ProductType.Model,
CatalogPrice = pvm.ProductType.CatalogPrice,
Id_ProductCompany = pvm.ProductType.Id_ProductCompany
};
db.ProductTypes.AddObject(productType);
db.Products.AddObject(product);
db.SaveChanges();
return RedirectToAction("Index", "Person");
}
return View(pvm);
}
My own validator :
public static ModelStateDictionary isValid(ProductType element)
{
ModelStateDictionary errors = new ModelStateDictionary();
if (!Regex.IsMatch(element.Model, @"^[a-zA-Z0-9\s][a-zA-Z-_0-9\s]+$"))
{
errors.AddModelError("Model", "Invalid name !");
}
return errors;
}
And where the message should be displayed :
<div class="editor-label">
Model :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.ProductType.Model, new { maxlength = 50 })
@Html.ValidationMessageFor(model => model.ProductType.Model)
</div>
IsValid(pvm)and then add the error likeerrors.AddModelError("ProductType.Model", "Invalid Name!");. A bit of a random guess here, don't actually know if using the dot will make MVC recognise the erroring field.