JavaScript client side function not firing for ASP custom validator - c#

I have the following ASP CustomValidator:
<asp:CustomValidator ID="CustomValidator2" runat="server"
EnableClientScript="true" OnServerValidate="ins_server" ClientValidationFunction ="ins_client"
ErrorMessage="CustomValidator"> * Insurance dates not valid without supporting attached document</asp:CustomValidator>
The following C# server side function:
protected void ins_server(object source, ServerValidateEventArgs args)
{
//new user
if (PageMode == PageModes.NewVessel)
{
if (fuAttachment.HasFile && datetimepickerinsend != null && datetimepickerinsstart != null)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
//existing user
if (PageMode == PageModes.EditVessel)
{
args.IsValid = true;
}
}
And also the following client side function in JavaScript stored in a file named customfunctions.js:
//declerations
var insurancestart;
var insuranceend;
var filesattached;
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
I also have the following global variable definition in the ASPX page the control sits on:
<script type="text/javascript">
var pagemode;
$(document).ready(function () {
// removed var to give global scope
pagemode = '<%=this.PageMode.ToString()%>';
});
</script>
My problem is
I have placed a breakpoint on the server side function, every time I click the submit button the server side code is being called and the page refreshes. If I debug in chrome I can see that all my JS variables have the expected values, it just seems like for some reason the client side JS function is not firing and is instead falling over to the server side function.

What was happening here was as #Justin-iurman pointed out, when the function returns true the server side function will also be called after the client. In my case though when I tested a false result I was still going straight to the server side function.
Turns out by pressing F12 in chrome and inspecting the console, I had an undefined error in my JS code. Moving the function in question out of the function used specifically for this page and into global context sorted the issue for me.

Related

Prevent Key Event on DevExress ASP.NET MVC SpinEdit

In a form, I have a spin edit control like this:
formLayoutSettings.Items.Add(i =>
{
i.FieldName = "FieldA";
i.NestedExtension().SpinEdit(s =>
{
s.Properties.MinValue = 1;
s.Properties.MaxValue = 9999999999999;
s.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
s.Properties.ClientInstanceName = "seFieldA";
s.Properties.Increment = 10;
s.ShowModelErrors = true;
s.Width = Unit.Percentage(100);
s.Properties.AllowMouseWheel = false;
s.Properties.ClientSideEvents.KeyDown = "OnFieldAKeyDown"; // This is the event heandeler
});
});
And the function:
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
ASPxClientUtils.PreventEventAndBubble(e.htmlEvent); // this doesn't work
ASPxClientUtils.PreventEvent(e.htmlEvent); // this either
}
}
My aim is to prevent the spin edit control value from changing when the user presses the Up key or Down keys. When I debug this, the if test inside the OnFieldAKeyDown works but PreventEventAndBubble and PreventEvent fails miserably. Also, is there any other way to do this with jquery ??
Thanks.
AFAIK, there is a workaround to prevent a user incrementing/decrementing SpinEdit value using up/down arrow keys without using PreventEvent or PreventEventAndBubble. When there's no public method available on JS side, you can try restore SpinEdit previous value in KeyDown event handler like this:
<script type="text/javascript">
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
// check if ASPxClientSpinEdit exists
if (typeof ASPxClientSpinEdit !== "undefined") {
ASPxClientSpinEdit.prototype.OnPageOrArrowKeyDown = function() {
// when user tries either increment or decrement, it returns last value instead
if (s.GetValue() != s.lastChangedValue) {
s.SetValue(s.lastChangedValue);
}
// if spinedit's minimum & maximum values also affected, set current limit
else {
s.maxValue = ASPxClientSpinEdit.MaxValue;
s.minValue = ASPxClientSpinEdit.MinValue;
}
}
}
}
}
</script>
Combine this function with jQuery may possible, any suggestions welcome.
Reference: https://www.devexpress.com/Support/Center/Question/Details/Q254514

Is there Any Possibility to show Alert Using C# code Inside the ASPxGridview Events

Code i written but Not showing alert :
protected void gvRole_RowInserted(objectsender,DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
if (e.Exception == null)
{
//I dont want like this
//((ASPxGridView)sender).JSProperties["cpInsertedRole"] = "New Role Inserted";
//I want Like
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "alert('New Role Inserted ');",true);
}
}
You need to check for JSProperties in call back end client script handler and generate alert based on JSProperties in that method.
<ClientSideEvents EndCallback="HandleGridCallBackEnd" />
function HandleCallBackEnd(s, e) {
var grid = ASPxClientControl.GetControlCollection().GetByName("ASPxGridView");
if (grid != undefined) {
if (grid.cpInsertedRole!= undefined
&& grid.cpInsertedRole.length > 0) {
alert(grid.cpInsertedRole);
grid.cpInsertedRole= '';
}
}
You can register javascript from C# as well if you want.
Using Java script I'm getting alert but using C# Not Getting
<ClientSideEvents EndCallback="function(s, e) {
if(typeof(gvAppUser.cpInsertedRole) != 'undefined')
{
alert(gvAppUser.cpInsertedRole);
delete gvAppUser.cpInsertedRole;
}
}" />

how to get client side confirm box value to make server side operations?

I am using Client script for confirm message box as follows
string script = "fadeScript";
ScriptManager.RegisterClientScriptBlock(this.Page, script.GetType(), "Script", "Closewindow();", true);
java script function:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
alert(Result);
if (Result == true) {
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert(txtConfirmresult.value);
return true;
}
else
{
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert('BYE');
return false;
}
}
</script>
I want to use the script return value in .cs file to excite procedure if it returns true. if it return false i have to stay on that particular page only. plz kindly help me on this
You can use __doPostBack(target, argument) to post back to the server. You can then evaluate __EVENTTARGET and __EVENTARGUMENT in the post data to see what you sent back and perform logic appropriately. Here is a link that provides a little more in depth information.
A quick example:
Script/Client side:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
alert(Result);
if (Result == true) {
var txtConfirmResult = document.getElementById('txtConfirmresult');
txtConfirmResult.value = Result;//assigning to hidden text box
alert(txtConfirmresult.value); //displaying for debug purposes
__doPostBack( 'txtConfirmresult', Result ); //sending back to server.
return true;
}
else
{
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert('BYE');
return false;
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
string target = Request["__EVENTTARGET"];
string argument = Request["__EVENTARGUMENT"];
if (target != null && target.Equals( "txtConfirmresult" ) )
{
this.DoSomeGreatServerSideProcessing(argument);
}
}
Updated to add slightly more correct variable names, but should work with your existing codebase assuming your script was working. I would be very careful using txtConfirmresult as your ID as that will only work if runat="server" is not set on the textbox. If that is the case, the ID will be prepended to denote container hierarchy.
I would suggest naming your "callbacks" very well, such as:
Script/Client side:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
if (Result) {
__doPostBack( 'UserConfirmedFormSubmission', "CloseWindow" ); //sending back to server.
return true;
}
else
{
return false;
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
string target = Request["__EVENTTARGET"];
string argument = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(target) && target.Equals("UserConfirmedFormSubmission"))
{
if ( !string.IsNullOrEmpty(argument) && argument.equals("CloseWindow"))
{
this.HandleUserRequestedCloseWinow();
}
}
}

trouble wih validation inside of asp wizard

I have a group of 5 textboxes and I am using an asp:wizard. I want to check to see if all of the textboxes are empty I want to fire a label named lblItemBlock. Nothing I have tried has worked so far and so i tried cutting it down even smaller to test. I made the label visible on the page and on the active step tried to set the visible property to false. and for whatever reason it does not work
here is what I have:
protected void OnActiveStepChanged(object sender, EventArgs e)
{
if (Wizard1.ActiveStepIndex == Wizard1.WizardSteps.IndexOf(this.WizardStep3))
{
lblItemBlock.Visible = false;
}
}
Use the textbox/input validator in asp.net
Use a custom validator with client side script. There is probably a better method with 5 inputs but I use this when I need to validate multiple inputs in unison. The following checks that at least one of the text boxes has content:
function searchValidate(oSrc, args) {
var fName = document.getElementById('<%= txtFName.ClientID %>').value;
var mName = document.getElementById('<%= txtMName.ClientID %>').value;
var lName = document.getElementById('<%= txtName.ClientID %>').value;
if (fName == "" && mName == "" && lName == "") {
args.IsValid = false;
} else {
args.IsValid = true;
}
}

Prevent page refresh on pressing F5

I have Created form with Server Side control like button..and also have written event on that..
Now runtime after click on the button i have refreshed the page by pressing F5.Page_load is executing fine but button1_click() event also firing...So how can i stop this event execution in this scenario.Please suggest me
Short Answer: Not possible
Longer Answer: No web site can block the browser's functionality as that would be a serious security concern for the browser.
Welcome to web development, there is no way to stop the page from refreshing and reposting, this is entirely a browser behavior.
There are work arounds though; one simple thing that you can do is after processing your button click, you can redirect the browser back to the page so that a refresh will not include a repost of your button press. Obviously this might require some other state management system (rather than view-state), maybe you can store your state in the Session.
<script type="text/javascript" language="javascript">
function checkKeyCode(evt)// for F5 disable
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if (event.keyCode == 116)//disable F5
{
evt.keyCode = 0;
return false
}
if (event.keyCode == 123) {
evt.keyCode = 0;
return false
}
if (event.keyCode == 93) {
evt.keyCode = 0;
return false
}
if (event.altKey == true && event.keyCode == 115) //disable alt-F4
{
evt.keyCode = 0;
return false
}
//alert(event.keyCode);
}
document.onkeydown = checkKeyCode;
</script>
Post this script on your master page or where u want to block F5 button.
You could potentially use:
window.onbeforeunload = function ()
{
return false;
}
This will display a prompt asking the user if they want to navigate away and may not be desired. (Plus, I don't know the extent of support)
The poster is using ASP.NET WebForms. In MVC, using the Post-Redirect-Get pattern, this would not be a problem.
But this has been solved for Webforms since 2004 (and even before that - I wrote a simple ticket solution in 2001) with this article: http://msdn.microsoft.com/en-us/library/ms379557.aspx
Basically the author creates a unique ticket associated with each request, and removes the validity of the ticket on first postback. Any accidental (or malicious) subsequent postbacks are ignored. It's wrapped up in a base page so it should be easy to add to any Webforms solution.
Its not really page refresh that you want to block, its page re-POST.
As already said, it's not possible on the client side because the refresh will replay what the browser did on the last action.
But you can trap it on the server side because the server can hold some infos to control the request.
The easiest way is to put a sort of RequestID in a hidden field on Page Load, store it somewhere like in the Session. And control its value on next POST to valid the request then override it to avoid re-POST with the same RequestID.
Maybe there's a better way :)
Your 'problem' is similar to a user double-click horror behavior : ASP.Net double-click problem
Do you have to refresh the page on the click of the button? Could you rewire the button to make an ajax call to submit the data? If so, then you would not need to worry about the page re-submitting on refresh.
The only solution for the F5 refresh problem is Response.Redirect. Please see my post on this topic.
https://stackoverflow.com/questions/12596152/asp-net-f5-browser-refresh-duplicate-record/12596153#12596153
I got some code that doesn't allow you to press F5 and/or Ctrl + R:
<!DOCTYPE html>
<html>
<head>
<title>
Key code test!
</title>
<script type="text/javascript">
var x, ctrlKeyPressed = false;
function keyDown(e){
x = e.charCode || e.keyCode;
document.getElementById("key").innerHTML = x;
if(x == 17) {
ctrlKeyPressed = true;
}
if(ctrlKeyPressed && x == 82) {
e.preventDefault();
} else if(x == 116) {
e.preventDefault();
}
}
function keyUp(e) {
x = e.charCode || e.keyCode;
if(x == 17) {
ctrlKeyPressed = false;
}
}
window.onload = function () {
document.onkeydown = function (e) {
keyDown(e);
};
document.onkeyup = function (e) {
keyUp(e);
};
}
</script>
</head>
<body>
Press a key!
<br/>
Key code: <div style="display:inline;" id="key">Nothing</div>
</body>
</html>

Categories