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();
DefaultModelBinder.ResourceClassKey = "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);
glToBeUpdated.UpdateDate = DateTime.Now;
glToBeUpdated.UpdateUser = this.CurrentUser;
glDataLayer.update(glToBeUpdated);
glDataLayer.submitChanges();
return RedirectToAction("Index");
}
catch
{
glDataLayer.abortChanges();
throw;
}
}