ASP.NET MVC: DataAnnotations - Displays an error message indicating that the field should be numeric

It seems like something works in DataAnnotations, like a user entering some text into a field that goes into an int will never reach the DataAnnotations code. It launches a model binding error and displays an error for the user. "The value" a "is not valid for field XXXX."

In any case, everything is very nice that it automatically handles this situation, but I really want to display an error message indicating a problem, for example. "Value" a "is not numeric. Enter a numeric value for field XXXX."

I tried the solutions outlined How to replace the default ModelState error message in Asp.net MVC 2? and ASP.NET MVC is a custom validation message for value types , but I can't get them to work.

It looks like my resource file is not readable at all, since here ( http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder.resourceclasskey.aspx ) it says: "If the property set an invalid key class (for example, a resource file that does not exist), MVC throws an exception. " and even if I change the line to DefaultModelBinder.ResourceClassKey = "asdfasdhfk", there will be no exceptions.

Does anyone have any idea?

EDIT: Here is the code. All this works minus when my Message.resx messages are not used. The code for Message.resx is automatically generated, so I won’t include it.

Thus, entering "a" in ProcessOrder results in a generic message, not what I typed in Message.resx for PropertyValueInvalid (and InvalidPropertyValue for a good estimate).

Application_Start Method

protected void Application_Start()
{            
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); //set dataanooations to be used
    DefaultModelBinder.ResourceClassKey = "Messages"; //set data annotations to look in messages.resx for the default messages
    ValidationExtensions.ResourceClassKey = "Messages";
}

Entity class

[MetadataType(typeof(GLMetaData))]
public partial class GL
{

}



public class GLMetaData
{
    public int TransRefId { get; set; }

    [DisplayName("Process Order")]
    public int? ProcessOrder { get; set; }

    [DisplayName("Trans Type")]
    [StringLength(50)]
    public string TransType { get; set; }

    [StringLength(100)]
    public string Description { get; set; }

    [DisplayName("GL Code")]
    [StringLength(20)]
    public string GLCode { get; set; }

    [DisplayName("Agents Credit No")]
    [StringLength(50)]
    public string AgentsCreditNo { get; set; }

    [Required]
    public bool Active { get; set; }
}

Controller action:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(GL glToBeUpdated)
    {
        try
        {
            if (!ModelState.IsValid)
                return View(glToBeUpdated);

            //set auto properties
            glToBeUpdated.UpdateDate = DateTime.Now;
            glToBeUpdated.UpdateUser = this.CurrentUser;

            glDataLayer.update(glToBeUpdated);

            glDataLayer.submitChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            glDataLayer.abortChanges();

            throw;
        }
    }
+2
source share
4 answers

, , , ModelState["XXXX"].Value.AttemptedValue nulled, Model, .

, , , ( " " " " ).

+1

MVC4 RC. ,

DefaultModelBinder.ResourceClassKey

. , .

, ():

 DefaultModelBinder.ResourceClassKey = typeof(App_GlobalResources.ValidationMessages).Name;

, jQuery .

@Html.TextBoxFor(m => m.Amount, new Dictionary<string,object>(){{"data-val-number","Invalid Number"}})

, .

:

@Html.TextBoxFor(m => m.Amount, new Dictionary<string, object>() {{ "data-val-number", HttpContext.GetGlobalResourceObject("ValidationMessages", "PropertyValueInvalid") } })
0

" " , Range, validatioin , .

    [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ContactNumberRequired")]
    [Range(0, int.MaxValue, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ValidContactNumber")]
    [Display(Name = "Contact Number")]
    public string ContactNumber { get; set; }

, ErrorMessageResourceName. Multi Language

0

All Articles