MVC - 更改属性比较错误信息 [英] MVC - Change Compare attribute error message

查看:207
本文介绍了MVC - 更改属性比较错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用我不得不从一个文本文件,而不是使用默认的错误信息收到错误信息的能力。这完美的作品所要求的属性(包括Serverside集团和客户方)。

In my MVC application I have the ability to get the error message from a text file instead of using the default error message. This works perfectly on the Required attribute (both Serverside and Clientside).

我现在需要做同样的在比较属性,但我无法弄清楚如何重写比较属性。

I now need to do the same with the Compare attribute, but I can't figure out how to override the Compare attribute.

有关的参考,这是我如何与所需的属性做(我想类似code将该一起工作在比较属性)...

For reference, this is how I am doing it with the Required attribute (I would like similar code to this to work with the Compare attribute)...

Public Class RequiredFieldAttribute
    Inherits ValidationAttribute
    Implements IClientValidatable

    Private innerAttribute As New RequiredAttribute()
    Private errormessagecontrolid As String

    Public Sub New(ErrorMessageControlID As String)

        Me.errormessagecontrolid = ErrorMessageControlID

    End Sub

    Protected Overrides Function IsValid(value As Object, validationContext As ValidationContext) As ValidationResult

        If Not innerAttribute.IsValid(value) Then
            Return New ValidationResult(ErrorMsgs.Text(Me.errormessagecontrolid))
        End If

        Return ValidationResult.Success

    End Function

    Public Function GetClientValidationRules(metadata As ModelMetadata, context As ControllerContext) As IEnumerable(Of ModelClientValidationRule) Implements IClientValidatable.GetClientValidationRules

        Dim result = New List(Of ModelClientValidationRule)

        Dim rule = New ModelClientValidationRule() With {.ErrorMessage = ErrorMsgs.Text(Me.errormessagecontrolid), .ValidationType = "required"}

        result.Add(rule)

        Return result

    End Function

End Class

以上,ErrorMsgs.Text是retieves从文本文件中的信息的功能。对我的模型我再申请这样的事情...

Above, ErrorMsgs.Text is the function that retieves the message from the text file. Against my model I then apply something like this...

<RequiredField("AccountDetailsPostcodeError")>
Public Property PostCode As String

你的系统会在名为AccountDetailsPost codeError条目中的文本文件。

The system then looks in the Text file for an entry called AccountDetailsPostcodeError.

我怎样才能实现与比较属性相同。目前,我有一个这样的硬codeD错误信息......

How can I achieve the same with the Compare attribute. At the moment I have a hard coded error message like this...

    <Compare("WebPassword", ErrorMessage:="The password and confirmation do not match.")>
    Public Property ConfirmWebPassword As String

修改:下面的修复建议可在C#中工作,但不会在VB.NET中工作,因此我的更复杂的要求,覆盖比较属性。我只是不知道如何正确地覆盖它。

Edit: The suggested fix below may work in C#, but won't work in VB.NET, hence my more complex requirement to override the Compare attribute. I just don't know how to correctly override it.

推荐答案

为什么要使用一个文本文件,为您的翻译和消息,.NET已建立在翻译选项。您可以使用的资源。利用资源的优点是,资源类型安全,它们被选中为编译时。你在哪里可以文本文件成为腐败/丢失。

Why use a text file for your translations and messages, .NET has build in options for translations. You can use resources. The advantage of using resources is that resources are type safe, they are checked as compile time. Where your textfile can become corrupt / missing.

下面的指南可以帮助你在一个MVC项目设置资源:

The following guide helps you with setting up resources in a Mvc project:

编辑缺省的汇编语言:


  • (C#)属性>大会信息>中性语言

  • (VB)我的项目>大会信息>中性语言

设置该语言为默认语言。 (在这个例子中我使用英语(美国)

Set this language to your default language. (For this example I use English (United States))

资源文件添加到您的项目。调用这个文件 Resource.resx 。打开这个文件。更改访问修饰符来公开和开始添加资源字符串。例如:

Add a resource file to your project. Call this file Resource.resx. Open this file. Change the Access Modifier to Public and start adding resource strings. For example:

添加你要支持其他资源文件,但它们命名为 Resource.LANGUAGE.resx 其中,语言是由其他区域性名称取代对方的语言。对于文化的名字,你可以检查此网址:<一href=\"http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx\">http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

Add for each other language you want to support another resource file but name them Resource.LANGUAGE.resx where LANGUAGE is replaced by the other culture name. For culture names you can check this url: http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

然后用本地化的字符串填充新的资源文件。例如:

Then fill the new resource file with the localized strings. For example:

然后你就可以在你的模型使用默认的本地化支持的属性:

Then you can in your Models use the default localization support of the attributes:

例如:

Imports System.ComponentModel.DataAnnotations
Public Class UserModel
    <Display(Name:="UserNameField", ResourceType:=GetType(My.Resources.Resource))>
    <Required(AllowEmptyStrings:=False, ErrorMessageResourceName:="RequiredUsername", ErrorMessageResourceType:=GetType(My.Resources.Resource))>
    Public Property UserName As String

    <Display(Name:="PasswordField", ResourceType:=GetType(My.Resources.Resource))>
    <MinLength(6, ErrorMessageResourceName:="PasswordLengthError", ErrorMessageResourceType:=GetType(My.Resources.Resource))>
    <Compare("PasswordAgain", ErrorMessageResourceName:="CompareError", ErrorMessageResourceType:=GetType(My.Resources.Resource))>
    <Required(AllowEmptyStrings:=False, ErrorMessageResourceName:="RequiredPassword", ErrorMessageResourceType:=GetType(My.Resources.Resource))>
    Public Property Password As String

    <Display(Name:="PasswordAgainField", ResourceType:=GetType(My.Resources.Resource))>
    <Required(AllowEmptyStrings:=False, ErrorMessageResourceName:="RequiredPasswordAgain", ErrorMessageResourceType:=GetType(My.Resources.Resource))>
    Public Property PasswordAgain As String
End Class

C#

using System.ComponentModel.DataAnnotations;
public class UserModel
{
    [Display(Name = "UserNameField", ResourceType = typeof(My.Resources.Resource))]
    [Required(AllowEmptyStrings = False, ErrorMessageResourceName = "RequiredUsername", ErrorMessageResourceType = typeof(My.Resources.Resource))]
    public string UserName;

    [Display(Name = "PasswordField", ResourceType = typeof(My.Resources.Resource))]
    [MinLength(6, ErrorMessageResourceName = "PasswordLengthError", ErrorMessageResourceType = typeof(My.Resources.Resource))]
    [Compare("PasswordAgain", ErrorMessageResourceName = "CompareError", ErrorMessageResourceType = typeof(My.Resources.Resource))]
    [Required(AllowEmptyStrings = False, ErrorMessageResourceName = "RequiredPassword", ErrorMessageResourceType = typeof(My.Resources.Resource))]
    public string Password;

    [Display(Name = "PasswordAgainField", ResourceType = typeof(My.Resources.Resource))]
    [Required(AllowEmptyStrings = False, ErrorMessageResourceName = "RequiredPasswordAgain", ErrorMessageResourceType = typeof(My.Resources.Resource))]
    public string PasswordAgain;
}

有关定位的属性需要知道静态属性的名称和静态类的哪里得到从属性(如上所示)的类型。

For localization the attribute needs to know the name of the static property and the type of the static class where to get the property from (as seen above).

然后在您的视图中使用 @ Html.ValidationSummary()让所有的错误信息,或使用

Then in your view use the @Html.ValidationSummary() to get all the error messages, or use


  • VB @ Html.ValidationMessageFor(功能(模型)model.Property)

  • C# @ Html.ValidationMessageFor(M = GT; m.Property)

  • VB @Html.ValidationMessageFor(Function(model) model.Property)
  • C# @Html.ValidationMessageFor(m => m.Property)

要得到具体的错误信息。

to get specific error messages.

有关的显示属性你可以使用:

For the display attribute you can use:


  • VB @ Html.DisplayNameFor(功能(模型)model.Property)

  • C# @ Html.DisplayNameFor(M = GT; m.Property)

  • VB @Html.DisplayNameFor(Function(model) model.Property)
  • C# @Html.DisplayNameFor(m => m.Property)

和最后但并非最不重要,你可以改变你的应用程序的语言,而不是通过编辑的Web.config在第一步中定义了中立的语言和改变像全球化标签所以:

And last but not least you can change the language of your app instead of your neutral language defined in step one by editing the Web.config and changing the globalization tag like so:


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <globalization uiCulture="nl" />
  </system.web>
</configuration>

如果你想改变从code,你应该修改 System.Threading.Thread.CurrentThread.CurrentUICulture 有关此信息的语言,我建议谷歌或其他SO问题。

If you want to change the language from code you should edit System.Threading.Thread.CurrentThread.CurrentUICulture for information about this I suggest google or another SO question.

有关这个问题,我很快就做出了表率项目提供一个准确的答案。项目可以在这里找到:结果
MvcVBTest.V1.zip

For this question I quickly made an example project to provide an accurate answer. Project can be found here:
MvcVBTest.V1.zip

如果你不想使用资源,但单一的文本文件,可以使用的资源框架使用相同的概念。您需要一个可以参考的静态属性的类。

If you don't want to use Resources but a single text file you can use the same concept the resource framework uses. You need a class that has static properties you can reference.

为此,我做了以下几件事:

For this purpose I did the following things:


  1. 我创建了一个名为资源(Resources.vb)类。

  2. 在这个类我添加称为子类资源

  3. 在该类我打开 resource.xml 我已映射到资源数组的静态构造函数

  4. 该数组然后转换成一个词典(字符串,字符串)

  5. 我创建了一个静态get属性在XML中的每个项目。而从字典
  6. 返回正确的项
  7. 我改变了的usermodel 类的<​​code>的ResourceType 参数

  1. I created a class called Resources (Resources.vb).
  2. In this class I added a sub class called Resource
  3. In the static constructor of this class I open resource.xml which I have mapped to an array of Resource
  4. This array is then converted to an Dictionary(Of String, String)
  5. I created an static get property for every item in the xml. And returned the right item from the Dictionary
  6. I changed the ResourceType parameter in the UserModel class

当然一点点清理。旧的资源可以被删除,全球化标签可以从 web.config文件中删除

And of course a little clean up. The old resources can be deleted and the globalization tag can be removed from the web.config.

现在所有的文本可以在 resource.xml 中找到的键值对。要添加另一条线,将其添加到XML并创建在资源类为它的属性。

Now all the text can be found in resource.xml as key value pairs. To add another line, add it to the XML and create a property for it in the Resource class.

有关此更新我更新了我的示例项目:结果
MvcVBTest.V2.zip

For this update I updated my example project:
MvcVBTest.V2.zip

这篇关于MVC - 更改属性比较错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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