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

I have a simple ASP.NET MVC website where users can browse products and place pre-orders. To post it, they must provide a 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);
}

ProductViewModelIt contains information about the product (name, description, price, etc.), and PreOrderProductCommandcontains only 3 stringproperties: Id, Nameand Email. Now I want to enable client-side validation Nameand Emailwith the help jquery.validateand cannot figure out how to implement it. All online tutorials say I should use this code:

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

, ProductViewModel , Email. PreOrderProductCommand.

? ?

0
2

Email ProductViewModel. :

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

HttpPost

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);
}
+2

, Email ProductViewModel.

, HtmlHelpers data-validation attrributes ViewModel, jquery.validate propeties.

, . ( PreOrderProductCommand). , , , .

- . ( html ) .

+2

Source: https://habr.com/ru/post/1613790/


All Articles