0

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>
1
  • 1
    Try passing the VM in the Validator: IsValid(pvm) and then add the error like errors.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. Commented Apr 18, 2013 at 12:31

1 Answer 1

2

Maybe changing it to

Maybe `errors.AddModelError("ProductType.Model", "Invalid name !");

would resolve your problem.

By the way, the best solution would be to use DataAnnotations and create your own ValidationAttribute:

public sealed class ValidNameAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        ....check regex here...
    }
}

Then you should decorate Name property with ValidName attribute.

EDIT:

You can also implement IValidatableObject interface in view model. ASP.NET MVC will pick it up and do automatic validation.

public class MyViewModel: IValidatableObject
{   
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (regexFails)
        {
            results.Add(new ValidationResult("Please enter valid name."));
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your first suggestion is not working, but thanks. However, I will have many fields to check... If I understand well, am I going to create a classe for each field? In my view model, is it impossible to check the regex?
@Traffy: Sorry. I made simple mistake. Can you check again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.