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?

winbacker
  • 637
  • 2
  • 6
  • 16

1 Answers1

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);
          }
});
Timothy Groote
  • 8,614
  • 26
  • 52
  • 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? – winbacker Aug 11 '14 at 14:46
  • oh you mean you're using validation *attributes* in your view model? – Timothy Groote Aug 11 '14 at 14:52
  • 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... – winbacker Aug 11 '14 at 14:54
  • There's a jQuery library built especially for that. for an example, see this question : http://stackoverflow.com/questions/14005773/use-asp-net-mvc-validation-with-jquery-ajax – Timothy Groote Aug 11 '14 at 15:22