Posts

Showing posts with the label Javascript

Step by step migration of ASP.NET Core 2.2 to 3.1

In order to upgrade/migrate asp.net core version to 3.1 following steps to be perform.
Download and install Visual Studio 2019 version 16.4 or higher.Download and install .NET Core 3.1  https://dotnet.microsoft.com/download/dotnet-core/3.1Upgrade the projects of solution to .NET Core 3.1 , because ASP.NET Core 3.1 requires it.Update existing Nuget packages to a version compatible with ASP.NET Core 3.1 in each projectUse IHost interface from a IHostBuilder instead of building and running a IWebHost from a IWebHostBuilder in Program.cs public static IHostBuilder CreateWebHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel() .UseSerilog() .UseStartup<Startup>(); }) Change AddMvc method has been replaced by AddControllers in Startup.cs of each projects.In Startup.cs,UseMvc method to be replaced by…

Disable button after click in asp.net

To prevent double submit a form by user we need to restrict the user to click the button again. The idea is that we will use JavaScript to disable the button once user clicks first time.

Add the following lines on .aspx page


<asp:Button ID="btnProcess" runat="server" onclick="btnProcess_Click" Text="Process" />
Add the following line on .aspx.cs page (Page_Load).


string strProcessScript = "this.value='Processing...';this.disabled=true;"; btnProcess.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(btnProcess, "").ToString());

This will disable Button, and then change the text of the button "Processing...", and then continue on with the server side event btnProcess_OnClick event handler.

Find IE version using javascript

Many Web designers use browser detection techniques to ensure that their sites display properly when viewed with specific browsers. Some browser detection techniques encounter problems when viewed with later versions of the browser they're tailored for. For example, many Web designers used Cascading Style Sheets (CSS) rules that relied on the implementation of CSS in Microsoft Internet Explorer 6 to detect that version of the browser. When Windows Internet Explorer 7 provided additional support for the Cascading Style Sheets, Level 2 (CSS2) standard, many of these rules (also known as "CSS hacks") failed to detect the new version of the browser. As a result, sites that relied on these rules no longer displayed as intended. When using browser detection techniques, use techniques that support current and future versions of the browser you're targeting.


The most common way to detect Internet Explorer is to use client-side scripting to parse the user-agent str…

File extension validation using javascript in MVC

This is article which demonstrate the validation of allowed file extension for upload of files in MVC using javascript. In this article i have used validation for valid image format like Jpeg, Jpg,Gif and png image format. If users ties to upload any other file apart from above mentioned file then the javascript function will shows proper message to user to select appropriate files.

I have used html input file control for uploading of files in MVC application.

following is the html code for it.


<body> <div style="height:50px; padding-bottom:20px;"> @using (@Html.BeginForm("Create","FileUpload",FormMethod.Post,new{ enctype = "multipart/form-data"})) { <input type="file" id="file1" name="sdf" style=" margin-top:0px;" onchange="if( CheckExtention(this.value) ) {parent.ShowHideImage(true);this.form.submit();}" /> } </div> </body>
and following is the ja…

Numeric validation on textbox/input on keydown event using JQuery

This is simple way to implement the numeric validation on textbox or input control using jquery. Firstly you need to use jquery selector for binding the keydown event to input control. Once you bind it it will only allow numeric keys and reject the alphabetical keys. Following is the code snippet of the numeric validation using Jquery.

$(document).ready(function () { $("#MobileNo").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyC…

Call server side methods asynchronously without having a postback using callback in asp.net

Callback is another fabulous way to communicate with server for light weight tasks. While working in ASP.NET, sometimes we need to call server side methods asynchronously without having a postback. Sometimes it is either a full page postback or partial page postback.

To Implement callback in asp.net following interfaces to me implement in the asp.net page

ICallbackICallbackEventHandler
Let us first implement ICallbackEventHandler to call the server side method asynchronously step-by-step. The following are the definition of two methods which we need to implement. RaiseCallbackEvent method invoke through JavaScript function.


public void RaiseCallbackEvent(string eventArgument) { //populate Customer object to return Customer customer = new Customer(); customer.Name = "Muhammad Adnan"; customer.Age = 24; //javascript serialization of Customer object System.Web.Script.Serialization.JavaScriptSerializer jss; jss = new System.Web.Script.Serialization.JavaScriptSe…

Populate Dropdown with jquery using JSON request in asp.net mvc3

In this Article i am going to demonstrate to fill the dropdownlist with jquery using JSON in asp.net mvc3. To achieve this task we need to write the following JavaScript code in view (.cshtml page)

@{ ViewBag.Title = "Products"; } <script type="text/javascript"> jquery(document).ready(function () { jquery("ddlCategory").change(function () { var idModel = jquery("#ddlCategory").val(); jquery.getJSON("product/items/", { category: idModel }, function (carData) { var select =jquery("#ddlitems"); select.empty(); select.append($('<option/>', { value: 0, text: "" })); jquery.each(carData, function (index, itemData) { …

ASP.NET Redirect to open a new browser window using javascript window.Open method

To  redirect the page in new window there is no readymade methode in asp.net. To overcome this lack of readymade function, we need to do some custom coding and it will only achieve by using javascript Window.Open Methode. I have created the methode in c#.nnet to redirect the desired page in new window.

Following is my methode defination..

public static void Redirect(string url, string target, string windowFeatures) { HttpContext context = HttpContext.Current; Page page = (Page)context.Handler; string script; if (!String.IsNullOrEmpty(windowFeatures)) { script = @"window.open(""{0}"", ""{1}"", ""{2}"");"; } else { script = @"window.open(""{0}"", ""{1}"");"; } script = String.Format(script, url, tar…

Highlight gridview row in update panel without posting back in asp net

When user selects particular row of gridview then that row should be highlighted. but in asp.net you do not have mechanism to to this task automatically. For this purpose you need to write some custom code, which includes some JavaScript code. to highlight the row selected by user follow the step below


For this you have to write this code in your code behind file in OnRowCreated event or your can also write this code in OnRowDataBound event of grid...
protected void ctlGridView_OnRowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')"); } }

then add following script to your aspx page in script tag
<script language="javascript" type="text/javascript"> var gridViewCtlId = '<%=ctlGridView.ClientID%>'; var gr…

How to get/find height and width of window using javascript

By knowing heigth and width of window we can place divs, messages,status wherever we want by using top left property of element. for that you should provide value of top and left to view in different monitors to get dynamic top left position you must find out the window width & height. following code will demostrate you to find out the window width & height which supports in  almost all browsers .



function windimension(){ if(window.innerHeight !==undefined) { var width= window.innerWidth; var height=window.innerHeight]; // most browsers } else{ // IE varieties var D= (document.body.clientWidth)? document.body: document.documentElement; var width= D.clientWidth; var height=D.clientHeight; } }

Hope this will help u.......

Adding events to DOM Elements in javascript by For IE, Mozilla, Opera browsers

To add events to DOM element Dynamically using javascript needs to write dis=fferent code for different browsers. Browsers Like Mozilla, Opera support the "W3C DOM Level 2 event binding mechanism"  which uses a function on DOM elements called addEventListener.

 Following the way to  add events to DOM element Dynamically for all browser.

if (window.addEventListener != null) { // Method for browsers that support addEventListener, e.g. Firefox, Opera, Safari window.addEventListener("focus", FocusFunction, true); window.addEventListener("blur", FocusLostFunction, true); } else { // e.g. Internet Explorer (also would work on Opera) window.attachEvent("onfocus", FocusFunction); document.attachEvent("onfocusout", FocusLostFunction); //focusout only works on document in IE } 

Hope this will help you guys........

Creation of Date Format function using javascript and Jquery

If you want to format the datetime string of database in your html file you need to get help from javascript.In javascript there is no pre define function exists to format date time string in dd MMM yyy. To accomplish the above task you need to write custom code. The following  is the custom function by using that you can format your datetime string in dd MMM yyyy format

first you need to write array which has all months


var gsMonthNames = new Array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' );
Then add following function in html file


function dFormat(date) { var result = ''; if (date != '') { var dateArray = date.split('/'); if (dateArray.length > 1) { result = dateArray[1] + " " + gsMonthNames[parseInt(dateArray[0])-1] + " " + …

Javascript keaboard events for function keys f1 to f12

Using the function keys in a web application is a dicey situation.  Several of the keys have specific uses in the browser and these keys should be avoided at all costs.  Additionally, the keys all have a semantic meaning in the UI standards of various operating systems.  But if you insist on using function keys, here’s a handy matrix for how they map and what events they can be used from.


KeyWindows Semantic MeaningonKeyDownonKeyPress*onKeyUpNotesF1Help112112N/ADon’t use this, it will open the browser’s help regardless of the way you process this key.F2Undo113113113F3Redo114114N/AF4New115115115F5Open/RefreshN/AN/A116Don’t use this… ever.  It always refreshes the browser and this functionality cannot be overridden.F6Close117117N/AF7Reply118118N/AIn Firefox this brings up the dialog to turn off caret browsing.  You should avoid this key.F8Forward119119119F9Send120120120F10Spell121121121F11Save/Full Screen122122122DON’T USE THIS!  This causes the browser to go full screen (just about…

Prompt user before navigate away from current page where user typed some text using javascript

In your application suppose user putting the data, then user accidently click the outside link or clode button of browser. In this situation user may loose his entered data.

To avoid this we can propmt user about his unsaved data by using symple javascript code.

This code will prompt the user about unsaved data in current page.

following is the javascript code snippet 


<html> <head> <title>window.onbeforeunload example</title> <script type="text/javascript"> var unsaved = false; window.onbeforeunload = function() { if (unsaved) { return "You have unsaved data. Are you sure you wish to leave this page."; } }; </script> </head> <body> <input type="text" id="input1" onkeydown="unsaved = true;"/> <input type="submit" id="input1" onclick="unsaved = true;"/> </body> </html>
Try your self and let me know your comments

Javascript print() method not printing Images ? then no problem i have a solution

If you are using window.Print() method of javascript to print the page but it prints only letters and does not print images of the page then use following solution for this problem

firstly try to use absolute url path in images src attribute like http://something.com/imger.jpg then it will be render correctly
secondly copy and paste below code in script tag 
function printContent(id){ var str=document.getElementById(id).innerHTML newwin=window.open('','printwin','left=0,top=0,width=1,height=1,menubar=no') newwin.document.write('<HTML>\n<HEAD>\n') newwin.document.write('\n') newwin.document.write('<script>\n') newwin.document.write('function chkstate(){\n') newwin.document.write('if(document.readyState=="complete"){\n') newwin.document.write('window.close()\n') newwin.document.write('}\n') newwin.document.write('else{\n') newwin.document.write('setTimeout("chkstate(…