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?
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?
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);
}
});