ASP.NET MVC - Custom validation message for value types

前端 未结 7 1897
粉色の甜心
粉色の甜心 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:12

    With the DefaultModelBinder it is possible to override the default required error message but unfortunately it would apply globally which IMHO renders it completely useless. But in case you decide to do it here's how:

    1. Add the App_GlobalResources folder to your ASP.NET site
    2. Add a resources file called Messages.resx
    3. Inside the resources file declare a new string resource with the key PropertyValueRequired and some value
    4. In Application_Start add the following line:

      DefaultModelBinder.ResourceClassKey = "Messages";
      

    As you can see there's no link between the model property you are validating and the error message.

    In conclusion it is better to write custom validation logic to handle this scenario. One way would be to use a nullable type (System.Nullable) and then:

    if (model.MyProperty == null || 
        /** Haven't tested if this condition is necessary **/ 
        !model.MyProperty.HasValue)
    {
        ModelState.AddModelError("MyProperty", "MyProperty is required");
    }
    

提交回复
热议问题