I have a button in ASP.NET. When the user clicks the button, I want to make some validation beforehand, so the postback only occurs if the validation method returns true.
My thought was to use the logic of the OnClientClick of the button. If you say OnClientClick=”return false;”, it won’t give a postback, while returning true will. However, that’s not working, as the resulting behaviour is it doesn’t make a postback even though what my jQuery method returns.
Currently I have:
Markup:
<asp:Button runat="server" ID="ReplyBtn" OnClientClick="return ValidateInput();" OnClick="ReplyBtn_Click" CssClass="btn-large btn-success"
Text="Answer" />
JavaScript:
function ValidateInput() {
var value = stripHtml(CKEDITOR.instances['ReplyBox'].getData()).trim();
var options = {
type: "POST",
url: "../../Services/ForumOperationService.svc/ReplyToPostFeedback",
data: '{"content":"' + value + '"}',
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#StatusReplyLbl").text(msg.ReplyToPostFeedbackResult);
if (msg.ReplyToPostFeedbackResult) {
return false;
} else {
return true;
}
},
error: function () {
return true;
}
};
$.ajax(options);
return false;
}
function stripHtml(str) {
return $('<div />', { html: str }).text();
}
So basically, what’s wrong with this code? And how can I perform validation on my button before making a postback?
Your function unconditionally returns
false, since you aren’t using the response from the ajax object. For example, let us assume your server side script returns the text “OK” if your validation succeeds. You could try something like this:Ideally, what you would do is unconditionally return false, and trigger a postback yourself in the success handler.