18

MVCの世界では、このビューモデルがあります...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

...そして、私の見解では、この種のこと...

<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>

私の質問: 名前を指定せずにこのフォームを送信すると、「FirstName フィールドが必要です」というメッセージが表示されます。

わかった。それで、私は行って、自分の財産を次のように変更します...

[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }    

..そして、「名フィールドは必須です」を取得します

これまでのところすべて順調です。

そこで、エラー メッセージに「First Name Blah Blah」と表示させたいと思います。すべてのプロパティに次のような注釈を付けずに、デフォルトのメッセージを上書きして DisplayName + "Blah Blah" を表示するにはどうすればよいですか

[Required(ErrorMessage = "First Name Blah Blah")]

乾杯、

ETFエアファックス

4

8 に答える 8

16
public class GenericRequired: RequiredAttribute
{
    public GenericRequired()
    {
        this.ErrorMessage = "{0} Blah blah"; 
    }
}
于 2009-12-18T22:49:51.300 に答える
13

RequiredAttribute は IClientValidatable を実装していないようです。そのため、RequiredAttribute をオーバーライドすると、クライアント側の検証が中断されます。

これが私がやったことであり、うまくいきます。これが誰かに役立つことを願っています。

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "whatever your error message is";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "required"
        };
    }
}
于 2012-03-28T19:10:33.083 に答える
13

サブクラス化せずにそれを行う方法を次に示しRequiredAttributeます。いくつかの属性アダプター クラスを作成するだけです。ここではErrorMessageResourceType/をErrorMessageResourceName(リソースと共に) 使用していますが、簡単に を設定ErrorMessageしたり、これらを設定する前にオーバーライドの存在を確認したりすることもできます。

Global.asax.cs:

public class MvcApplication : HttpApplication {
    protected void Application_Start() {
        // other stuff here ...
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
    }
}

private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
    public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValRequired";
    }
}

private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
    public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValStringLength";
    }
}

この例では、Resources.resx という名前のリソース ファイルを作成しValRequired、新しい必須の既定のメッセージValStringLengthとして、文字列の長さが既定のメッセージを超えていることを示します。{0}は、 で設定できるフィールドの名前を受け取ることに注意してください[Display(Name = "Field Name")]

于 2014-04-20T07:39:31.980 に答える
3

変えるだけ

[Required] 

[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]
于 2012-02-03T21:05:08.263 に答える
0

独自の属性を書くことができます:

public class MyRequiredAttribute : ValidationAttribute
{
    MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
    {

    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }
        string str = value as string;
        if (str != null)
        {
            return (str.Trim().Length != 0);
        }
        return true;
    }
}

これは Reflector からの RequiredAttribute のコピーで、エラー メッセージが変更されています。

于 2009-11-27T20:25:07.453 に答える
0
using Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Mvc;

public class CustomRequiredAttribute : RequiredAttribute,  IClientValidatable
{
    public CustomRequiredAttribute()
    {
        ErrorMessageResourceType = typeof(ValidationResource);
        ErrorMessageResourceName = "RequiredErrorMessage";
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {


        yield return new ModelClientValidationRule
        {
            ErrorMessage = GetRequiredMessage(metadata.DisplayName),
            ValidationType = "required"
        };
    }


    private string GetRequiredMessage(string displayName) {

        return displayName + " " + Resources.ValidationResource.RequiredErrorMessageClient;        

    }


}

App_GlobalResources/ValidationResource.resx

ここに画像の説明を入力

データ注釈を使用するようになりました

[CustomRequired]
于 2016-05-07T13:35:05.283 に答える
-1

これは私にとってはうまくいきました。コード内のコメントを注意深く読んでください。(チャドの回答に基づく)。

 // Keep the name the same as the original, it helps trigger the original javascript 
 // function for client side validation.

        public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
            {
                public RequiredAttribute()
                {
                    this.ErrorMessage = "Message" // doesnt get called again. only once.
                }

                public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                {
                    yield return new ModelClientValidationRule
                    {
                        ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
                        ValidationType = "required"
                    };
                }
            }
于 2012-04-11T10:16:05.327 に答える