我想知道是否可以通过 View 模型 (MVC) 返回一些值给客户端,或者在知道验证结果后在客户端上执行一些 JavaScript。
有人熟悉执行此操作的合适类和方法吗?
最佳答案
当然可以,因为普通的 AJAX 请求会返回答案。 如果您使这个答案有效 JSON 并从中重新组装客户端模型,然后验证它并相应地运行代码。
我通常通过在 MVC 的 ajax 回复中添加“成功”和“有效负载”来解决此问题。 所有客户端 Ajax 调用都会检查“成功”值,并决定相应地使用有效负载。
例如:
回复是:
{success : false, payload:"A null pointer occurred somehwere."}
或者:
{success : true, payload:{id:12, label:"banana"}}
然后我可以在我的 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);
}
});
关于javascript - 在 asp.net 中服务器端验证后可以运行自定义代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245205/