holdenmcgrohen
holdenmcgrohen

Reputation: 1063

ASP.NET MVC - client side validation when using view models

I have a really simple ASP.NET MVC website where users can browse products and place a pre-order. To place it they have to specify the name and email address. The controller looks like this:

[HttpGet]
public ActionResult Product(string id)
{
    return View(new ProductViewModel(id));
}

[HttpPost]
public ActionResult Product(PreOrderProductCommand command)
{
    if (ModelState.IsValid)
    {
        command.Process();
        return View("ThankYou");
    }
    else
        return Product(command.Id);
}

ProductViewModel contains various product info (name, description, price, etc.) and PreOrderProductCommand contains just 3 string properties: Id, Name and Email. Now I want to enable client side validation of Name and Email using jquery.validate and can't figure out how to implemet it. All the tutorials on the web say that I have to use code like this:

@Html.ValidationMessageFor(model => model.Email)

But the problem is that my view has ProductViewModel as a model and this class doesn't have the property Email. This property and its validation logic reside in PreOrderProductCommand.

What's the right way to implement client-side validation in this case? What am I missing?

Upvotes: 0

Views: 1570

Answers (2)

Dez79
Dez79

Reputation: 577

You need to add the Email property to your ProductViewModel. With the following attributes:

[DisplayName("Email")]
[Required(ErrorMessage = "Please enter email")]
public string email { get; set; }

Then pass this model into your HttpPost controller

and populate your command class from within i.e.

[HttpPost]
public ActionResult Product(ProductViewModel model)
{

PreOrderProductCommand command = new PreOrderProductCommand();

command.Id = model.id;    
command.Email = model.email;

if (ModelState.IsValid)
{
    command.Process();
    return View("ThankYou");
}
else
    return Product(command.Id);
}

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

No, for client side validation you should add Email property to your ProductViewModel.

That happened becouse HtmlHelpers create data-validation attrributes in inputs according to Attributes above ViewModel properties and then jquery.validate check this propeties.

Your server side validation works becouse it uses different mechanism. It checks validation properties on server after binding request properties to your model (in your case PreOrderProductCommand model). Bunding happends according to Names of properties so if you have right names everything should be fine.

The only other way to do it is to create markup manually with validation attridutes that you need. (I mean plain html in your View) But i wouldn't recommend it.

Upvotes: 1

Related Questions