AddModelError question


I’m trying to add a model error onClick.

I’have my ViewModel:

public class HomeViewModel : MasterPageViewModel {
     public MyModel Model {get;set;} = new MyModel();


    public async Task OnClick(){
         if(Model.SomeBoolean == false) {
                    this.AddModelError(vm => vm.Model.SomeBoolean, "The error message");

When trying to add the error like this I get a 500:

ValidationTarget (MyModel) must be equal to specified view model (HomeViewModel).

What am I doing wrong?

Best regards,

This looks like an error from an DotVVM 3.x, this limitation should be lifted as of 4.0. Are you using an older version or did we forget to remove this error?

Anyway, the problem is that all validation paths sent from server were relative to the Validation.Target set in dothtml markup. This means that it’s impossible to attach error anywhere else than on the one object which is the validation target. In this case it seems that you are indeed trying to attach the error to the correct object, but DotVVM just can’t figure this out. I think there should be another AddModelError method on Context which allows you to put in the correct viewmodel, even if it doesnt implement IDotvvmViewModel - Context.AddModelError(this.Model, vm => vm.SomeBoolean, ...). If MyModel implements IDotvvmViewModel, you can simply use this.Model.AddModelError(vm => vm.SomeBoolean, ...).

Context.AddModelError(this.Model, vm => vm.SomeBoolean, …) don’t work for my, it doesn’t expect 3 arguments and I can’t use the 2nd option.
Yes it’s running with DotVVM 3.x

Sorry, we made it an extension method later. In your version, this should work:

ValidationErrorFactory.AddModelError(this.Model, vm => vm.SomeProperty, "msg", context); 

You can also add the errors manually to the context.ModelState collection, however, beware that this change in the v4 version.

1 Like

That’s working perfectly now thank you. Yeah I’ll problably update to DotVVM 4.x later. The way I was doing would work in DotVVM 4.x ?

Yes, your original code is exactly as I’d do it in version 4

1 Like

Thank you very much for the help.