如何在MVC3中对同一对象的实例显示不同的Required消息? [英] How do I show a different Required message to instances of the same object in MVC3?

查看:88
本文介绍了如何在MVC3中对同一对象的实例显示不同的Required消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Razor MVC3项目,该项目具有两种形式的用户记录,一个用于关键联系人,一个用于备用联系人.例如;

I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;

public class User
{
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }
}

除用户无法填写字段的小问题(要求输入姓氏")外,所有其他方法都可以很好地进行验证,但我想向用户指出缺少名字字段之一的问题.例如需要备份联系人的名字"或需要关键联系人的名字".

Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.

理想情况下,我想在类中使用[Required]注释,因为该注释在其他地方使用.

Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.

这似乎是可能遗漏且难以实现的小案例之一,但请证明我错了.

This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.

瑞安

推荐答案

可以完成此操作的一种方法是为此屏幕使用单独的视图模型,而不是使用包含所有错误消息的单个User模型.在新的视图模型中,您可能具有一个BackupContactFirstName属性,KeyContactFirstName属性等,每个属性都有其单独的错误消息. (或者,该视图模型可以包含单独的用户模型作为属性,但是我发现Microsoft的客户端验证不适用于复杂的模型,并且更喜欢平面属性.)

One way you can accomplish this is with a separate view model for this screen, instead of a single User model with all the error messages. In the new view model, you could have a BackupContactFirstName property, KeyContactFirstName property, etc each with its separate error message. (Alternatively this view model could contain separate User models as properties, but I've found that Microsoft's client validation doesn't play well with complex models and prefers flat properties).

您的视图模型如下所示:

Your view model would look like this:

public class MySpecialScreenViewModel
{
    [Required(ErrorMessage = "Backup contact first name is required")]
    public string BackupContactFirstName { get; set; }


    [Required(ErrorMessage = "Key contact first name is required")]
    public string KeyContactFirstName { get; set; }
}

然后将您的视图模型传递给这样的视图:

Then pass your view model to the view like this:

@model MySpecialScreenViewModel
...

您的后控制器操作将从视图模型中收集属性(或将它们映射到单独的用户模型),并将其传递给适当的数据处理方法.

Your post controller action would collect the properties from the view model (or map them to separate User models) and pass them to the appropriate data processing methods.

这篇关于如何在MVC3中对同一对象的实例显示不同的Required消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆