2

モデルで[maxlength(2)]を使用しているasp.net mvc 4を使用していますが、クライアント側の検証で機能していません。asp.netmvcを初めて使用します。コードは次のとおりです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace RestrauntsMVC.Models
{
  public class Restraunts
  {

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [MaxLength(2),MinLength(1)]
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
  }
}
4

2 に答える 2

7

私は答えmyslefが機能することを発見しました。Maxlengthとminlengthは整数ではなく文字列用です。

using System;
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  
namespace RestrauntsMVC.Models
{
public class Restraunts
{

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [Range(1,10,ErrorMessage="Rating must between 1 to 10")]        
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
}
}
于 2012-11-29T17:08:48.963 に答える
2

他の言及と同様に、文字列のみを対象としているので、独自のValidationAttributeを作成するのはどうですか?

using System.ComponentModel.DataAnnotations;

internal class MaxDigitsAttribute : ValidationAttribute
{
    private int Max,
                Min;

    public MaxDigitsAttribute(int max, int min = 0)
    {
        Max = max;
        Min = min;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!IsValid(value))
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }

    public override bool IsValid(object value)
    {
        // you could do any custom validation you like
        if (value is int)
        {
            var stringValue = "" + (int)value;
            var length = stringValue.Length;
            if (length >= Min && length <= Max)
                return true;
        }

        return false;
    }
}
于 2014-03-21T16:08:12.493 に答える