Surendra Sharma

Surendra Sharma

Search This Blog

Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, July 15, 2015

Didn’t getting selected value of JQuery populated dropdownlist on server side



I was working on ASP.NET page which contains Country and State dropdown list. I filled country dropdown using JQuery AJAX. Now on selected value of Country I want to fill related states. I told my manager that it’s a simple task and will complete it in 3 hours including testing.

And next one hour I was just trying to get value of selected country in C# ;)

I tried with ddlCountry.selectedvalue but OMG I was not getting selected value.

How to get the dropdown selected value?

As we are filling dropdown list at client side so server side code don’t have any idea about the filled items. So in this situation use Request object as below

string country = Request[ddlCountry.UniqueID];

Now I was able to get the selected country in C# code.

Keep in mind that after getting value if there is another postback, you will not get the same country from Request[ddlCountry.UniqueID]. So during first time itself keep it in Viewstate so that you can use it after several post back as well.

One last thing, I completed this task in 3 hours as I told to my manager :)

Please leave your comments or share this tip if it’s useful for you.

Thursday, April 30, 2015

How to add HTML page in Sitecore?

My client requested to add HTML page in Sitecore project and link it to one of the item in footer. I asked to myself WTF, what kind of requirement is this? How to do this?

But finally I completed this. Here are the quick steps.

1. Add HTML page in any folder of your .NET project. Let’s say it is "/HTMLPages/faq.htm"
2. Add complete path of this HTML page in “IgnoreUrlPrefixes“ in web.config file so that Sitecore should not process this page request and ignore it. Let’s ASP.NET should serve this page request without using Sitecore.

<setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/HTMLPages/faq.htm"/>

3.    Specify this page in General Link field of Sitecore item. But the problem is it’s neither the internal link nor the external link. So how to provide the link so that it should take protocol and domain name automatically.

Here I use the Insert JavaScript option of General Link field as

javascript:window.open(window.location.protocol + "//" + window.location.host   + '/HTMLPages/faq.htm');

Here is screenshot of the General link field setting



Now when it renders, the item open this page in new window and take this page as a part of current website.

Sometimes client requirement plays a major role to improve our skills.

Please leave your comments or share this trick if it’s useful for you.

Monday, April 13, 2015

How to do versioning of JS and CSS files in ASP.NET

Whenever user access any website - images, JS and CSS are cached by browser. But if JS and CSS are updated on server still client browser refer the old JS and CSS. That’s very bad. It’s always good practice to provide the latest copy of CSS and JS to client browser.

But how to do it in ASP.NET to make sure browser is getting the updated files.

To solve this, we can use query string with JS and CSS.

For CSS, take one literal in <Head> section of aspx page as below

<head runat="server">
<asp:Literal ID="ltStyleCss" runat="server" Text="" ></asp:Literal>
</head>

Write below code

public string CurrentVersion = "";

protected void Page_Load(object sender, EventArgs e)
{
CurrentVersion = DateTime.Today.ToString("MMddyyyy") + "_" + DateTime.Now.Hour.ToString();

ltStyleCss.Text = string.Format("<link href=\"/ css/style.css?ver={0}\" rel=\"stylesheet\" />", CurrentVersion) + System.Environment.NewLine;


Here we are declaring version for each hour of the day.

You can do it for each request by specifyin current datetime, but problem with that approach is that it affects network bandwidth. So per hour solution is better.

It’s very easy to specify it for JS by directly passing the version variable as query string  

<script src="/Presentation/scripts/jquery.js?ver=<%=CurrentVersion%>"></script>

Pretty simple for JS but you can’t achieve the same way for CSS. Let me know if you can do it for CSS as well.


Please leave your comments or share this tip if it’s useful for you.

Sunday, April 12, 2015

How to implement Facebook Tag API script or Facebook Analytic tracking script

Facebook analytic is great way to track your website access by analyzing custom audience source. Facebook called it as Facebook Tag API.

To work with this you need Facebook tracking ID. I represented it as “NNNNN”. In project store it either in web.config or database. Below is script that you need to place it before the end of </body> section of webpage.

    <script>(function () {
    var _fbq = window._fbq || (window._fbq = []);
    if (!_fbq.loaded) {
        var fbds = document.createElement('script');
        fbds.async = true;
        fbds.src = '//connect.facebook.net/en_US/fbds.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(fbds, s);
        _fbq.loaded = true;
    }
    _fbq.push(['addPixelId', 'NNNNN']);
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'PixelInitialized', {}]);
    </script>
    <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?id=NNNNN&amp;ev=PixelInitialized" /></noscript>

This much of information is enough to implement it in any web application like ASP.NET etc. Though programmer don’t like much theoretical reading however you can read more from https://developers.facebook.com/docs/ads-for-websites/tag-api

Please leave your comments or share this script if it’s useful for you.

Saturday, March 7, 2015

How to find any word in string using Jquery

This is simple but very useful method in Jquery to find any word or presence of any substring in any string.

if ($('#txtSearch').val().indexOf('?') < 0)

Here if “?” is present in textbox value then indexIf() method return the position of word in string otherwise return -1 in case of not present.


Please leave your comments or share this tip if it’s useful for you.

Friday, March 6, 2015

How to access the current URL using JavaScript

Many times we need to access current URL of browser using Javascript. Suppose if there is URL like http://www.example.com/guest/index.aspx , now you can access this URL in different pieces as below

alert(window.location.protocol); // display "http:"
alert(window.location.host); // display “www.example.com"
alert(window.location.pathname); // display "guest/example.aspx"

You can get the complete and full URL by concatenating all these different parts

var currentURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;


Please leave your comments or share this tip if it’s useful for you.

Wednesday, February 18, 2015

Google Analytic tracking script

Google analytic is great way to track your website access and view of different pages.

Question is how to implement analytic in your web project?

To work with this you need Google tracking ID. I represented it as “NNNNN”. In project store it either in web.config or database. Below is script that you need to place it before the end of </body> section of webpage.

<script type="text/javascript">

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'NNNNN']);
    _gaq.push(['_trackPageview']);

    (function () {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

</script>


Please leave your comments or share this script if it’s useful for you.

Wednesday, August 6, 2014

How to show multiple messages in alert box in JavaScript?

An alert box is used to pop up the information where user has to click “OK”.

alert("This is single line message.");

Generally we are showing single line message in alert box. But do you know how to show multiple message in single alert box?

Trick is to use “\n” after every message to separate one message with other like

alert('-1. Tajmahal in India. \n\n-2. Pyramids in Egypt. \n\n-3. Great wall of China.');

Here I want separation of two lines between each message, so I used “\n\n”.

So finally it should look like this




Please leave your comments or share this tip if it’s useful for you.

Tuesday, January 21, 2014

JavaScript error Unable to get Value of the property 'length': object is null or undefined.

If your website is working fine but some user getting JavaScript error as “Unable to get Value of the property 'length': object is null or undefined.” Then problem is with their browser cache.

Delete browser complete history by uncheck “Preserve Favorites website data” and select rest of option as shown below as shown below





Please leave your comments or share this tip if it’s useful for you.