ASP.NET MVC - Custom validation message for value types

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

    In ASP.NET MVC 1, I met this problem too.

    In my project, there is a model or business object named "Entry", and its primary key EntryId is int? type, and the value of EntryId can be allowd to input by users.

    So the problem is, when the field is blank or zero or some integer value that has existed, the custom error messages can be shown well, but if the value is some non-integer value like "a", i can not find a way to use the custom message to replace the default message like "The value 'a' is invalid".

    when i track the error message in ModelState, i found when the value is non-integer, there will be two errors related to EntryId, and the first item's error message is blank...

    Now i have to use such an ugly code to hack the problem.

    if (ModelState["EntryId"].Errors.Count > 1)
    {
        ModelState["EntryId"].Errors.Clear(); //should not use ModelState["EntryId"].remove();
        ModelState.AddModelError("EntryId", "必须为大于0的整数"); //必须为大于0的整数 means "it should be an integer value and great than 0"
    }  
    

    but this makes controller fat, hope there is a real solution to solve it.

提交回复
热议问题