0

I'm wondering if I can either return some values through a viewmodel (MVC) to the client, or execute some javascript on the client after validation results are known.

Is anyone familiar with suitable classes and methods for doing this?

1 Answer 1

2

Of course you can, since a normal AJAX request returns an answer. If you make this answer valid JSON and reassemble a client side model out of it, then validate it and run code accordingly.

I usually solve this by adding a "success" and "payload" to my ajax replies from MVC. All client side Ajax calls check for the "success" value, and decide to use the payload accordingly.

for instance :

reply is :

{success : false, payload:"A null pointer occurred somehwere."}

or:

{success : true, payload:{id:12, label:"banana"}}

then i can do this in my ajax call :

var yourViewmodel = {id:null, label:"banana"};

jQuery.ajax({
          cache: false,
          url: "./save",
          type: "POST",
          data: yourViewmodel,
          success: function (response) {
              if(response.success == true)
              {
                 if(!validate(response.payload))
                 {
                    //something about the response payload still was not valid!
                 }
                 else
                 {
                    //here we can do whatever we want to do if the response was valid.
                    onAfterValidate(response.payload);
                 }
              }
              else
              {
                 alert("An error occurred : " + response.payload);
              }
          },
          error: function(data, errorThrown)
          {
              alert('request failed :'+errorThrown);
          }
});
Sign up to request clarification or add additional context in comments.

4 Comments

I'm currently validationg with server side classes that extend the Validation Attribute class. These are bound to my model which present the view to the client. I don't believe that I have access to the ajax code that is allowing this communication...do you know how I can gain access to it?
oh you mean you're using validation attributes in your view model?
Yes, sorry I guess I should have mentioned that. I have written custom validators that are being applied using attributes above fields in my viewmodel that are subject to validation...
There's a jQuery library built especially for that. for an example, see this question : stackoverflow.com/questions/14005773/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.