ASP.NET MVC - Custom validation message for value types

前端 未结 7 1892
粉色の甜心
粉色の甜心 2020-11-30 02:46

When I use UpdateModel or TryUpdateModel, the MVC framework is smart enough to know if you are trying to pass in a null into a value type (e.g. the user forgets to fill out

相关标签:
7条回答
  • 2020-11-30 03:17

    I've been using the awesome xVal validation framework. It lets me do all my validation in the model (Even LINQ-SQL :)). It also emits the javascript required for client side validation.

    EDIT: Sorry left out the link for how to get it working for LINQ-SQL

    The basic workflow goes something like this.

    public partial class YourClass
    {
        [Required(ErrorMessage = "Property is required.")]
        [StringLength(200)]
        public string SomeProperty{ get; set; }
    }
    

    try
    {
        // Validate the instance of your object
        var obj = new YourClass() { SomeProperty = "" }
        var errors = DataAnnotationsValidationRunner.GetErrors(obj);
        // Do some more stuff e.g. Insert into database
    }
    catch (RulesException ex)
    {
        // e.g. control name 'Prefix.Title'
        ex.AddModelStateErrors(ModelState, "Prefix");   
        ModelState.SetModelValue("Prefix.Title", new ValueProviderResult(ValueProvider["Prefix.Title"].AttemptedValue, collection["Prefix.Title"], System.Globalization.CultureInfo.CurrentCulture));
    
    }
    
    0 讨论(0)
提交回复
热议问题