ASP.NET MVC - 使用视图模型时,客户端验证 [英] ASP.NET MVC - client side validation when using view models
问题描述
我有一个非常简单的ASP.NET MVC网站,用户可以浏览产品和放置pre-秩序。要将其放在他们指定的姓名和电子邮件地址。该控制器是这样的:
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
包含各种产品信息(名称,描述,价格等)和 preOrderProductCommand
包含短短3 字符串
属性:编号
,名称
和电子邮件
。
现在,我想启用名称的客户端验证
和电子邮件
使用 jquery.validate
并不能弄清楚如何implemet它。所有在网络上的教程说,我必须使用code是这样的:
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)
但问题是,我的观点有ProductViewModel为模型而这个类没有属性电子邮件
。这个属性和它的验证逻辑驻留在 preOrderProductCommand
。
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?
推荐答案
您需要将电子邮件属性添加到您的ProductViewModel。具有以下属性:
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; }
那么这种模式传递到您的HttpPost控制器
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);
}
这篇关于ASP.NET MVC - 使用视图模型时,客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!