[英]Can you run custom code after server-side validation in asp.net?
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. 我想知道我是否可以通过视图模型(MVC)向客户端返回一些值,或者在知道验证结果之后在客户端上执行一些JavaScript。
Is anyone familiar with suitable classes and methods for doing this? 是否有人熟悉适合的类和方法?
Of course you can, since a normal AJAX request returns an answer. 当然可以,因为正常的AJAX请求会返回答案。 If you make this answer valid JSON and reassemble a client side model out of it, then validate it and run code accordingly.
如果使此答案有效为JSON并从中重组出客户端模型,则对其进行验证并相应地运行代码。
I usually solve this by adding a "success" and "payload" to my ajax replies from MVC. 我通常通过在MVC的ajax答复中添加“成功”和“有效载荷”来解决此问题。 All client side Ajax calls check for the "success" value, and decide to use the payload accordingly.
所有客户端Ajax调用都会检查“成功”值,并决定相应地使用有效负载。
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 : 那么我可以在我的ajax电话中做到这一点:
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.