Ganesh_Devlekar Ganesh_Devlekar - 2 months ago 14
ASP.NET (C#) Question

Adding JavaScript To Many Pages(More than 500) in asp.net without MasterPage

I am working on Project in which there are more than 500 .aspx pages(Popups uses ShowModelDialog) I want Suppress/Disable Enter Key for each Page

I want to Add Below Code for Every page (all Popup )or for every Request made by User. Unfortunately There is no master page in the project

<script type="text/javascript">

function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

document.onkeypress = stopRKey;

</script>

void Application_BeginRequest(object sender, EventArgs e)
{
// Code that runs on application shutdown
System.Web.UI.Page mypage = (System.Web.UI.Page)HttpContext.Current.Handler;
if (mypage != null)
{
mypage.ClientScript.RegisterClientScriptBlock(GetType(), "MyScriptKey", "alert('hi')", true);
}

}


I try to add this script in
Global.asax
in
Application_BeginRequest
but no luck

Answer

I used Application_PreRequestHandlerExecute event in Global.asax file and it worked.

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        HttpContext context = ((HttpApplication)sender).Context;
        Page mypage = context.CurrentHandler as Page;
        if (mypage != null)
        {

            mypage.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), @"function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && (node.type=='text'))  {return false;}
           }
            document.onkeypress = stopRKey; ", true);


            mypage.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), @"function validatedot(val, evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);

            y = val.value.split(/\./);

            var regex = /[0-9]|\./;

            if (y.length > 1 && key == '.') {

                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
            if (!regex.test(key)) {

                if (theEvent.keyCode != 8 && theEvent.keyCode != 9) {
                    //alert('Enter only number');
                    //alert(theEvent.keyCode);
                    theEvent.returnValue = false;
                    if (theEvent.preventDefault) theEvent.preventDefault();
                }
            }


        }", true);
        }

    }
Comments