开发者

ValidationMessageFor returns no information when calling modelState.AddModelStateError

开发者 https://www.devze.com 2023-01-21 12:55 出处:网络
I created a class that 开发者_Python百科implements the IModelBinder interface. Within a method of that class I basically retrieve some values and try to validate them. If the validation fails, I add u

I created a class that 开发者_Python百科implements the IModelBinder interface. Within a method of that class I basically retrieve some values and try to validate them. If the validation fails, I add update the model state with necessary information like below:

        DateTime mydate;
        if (!DateTime.TryParse(convValue,out mydate))
        {
            bindingContext.ModelState.AddModelError("Date", "Date was crap");
        }

The problem is that Html.ValidationMessageFor(m => m.Model) returns no value. I looked at the MVC source code and found out that a proper key with id "Date" can't be found in the ModelState dictionary.

Why is that ? The controller that returns the view have access to the model state and can enumerate over ModelState.Errors

Thanks, Thomas


Is "Date" the name of the property you are validating?

The first parameter of ModelState.AddModelError should either be the name of the property you want the validation message to display for, or left as string.Empty if you only want the error to display in in the validation summary.

If you want to display an error message that isn't tied to a specific property of your viewmodel, you could call <%: Html.ValidationMessage("Date") %> in your view to display that particular message if it has been set.

Edit: just realised how old this question is. Ah well, might come in handy anyway...

0

精彩评论

暂无评论...
验证码 换一张
取 消