Thursday, 19 April 2012

textbox watermark javascript jquery

How to add watermark to single/multiple textbox control using javascript/jquery js in Asp.net C# code:

The below sample has two approach by using jquery as well as javascript js.


Sample ASPX source code sample:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

/* js on load method*/  

$(document).ready(function() {
     var watermark = 'Enter your text';
     $('#txtBox').blur(function(){
      if ($(this).val().length == 0)
        $(this).val(watermark).addClass('watermark');
     }).focus(function(){
      if ($(this).val() == watermark)
        $(this).val('').removeClass('watermark');
     }).val(watermark).addClass('watermark');
    });

/* javascript function*/   
    function watermark(inputId,text){
      var inputBox = document.getElementById(inputId);
        if (inputBox.value.length > 0){
          if (inputBox.value == text)
            inputBox.value = '';
        }
        else
          inputBox.value = text;
    }
    </script>
  
    <style type="text/css">
    #txtBox.watermark { color: #999; } /*Gray color*/
    </style>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
  
    <asp:TextBox ID="txtName" runat="server" Text="Enter your name" onfocus="watermark(this.id,'Enter your name');" onblur="watermark(this.id,'Enter your name');"></asp:TextBox>
    <asp:TextBox ID="txtAddress" runat="server" Text="Enter your Address" onfocus="watermark(this.id,'Enter your Address');" onblur="watermark(this.id,'Enter your Address');"></asp:TextBox>
    </div>
    </form>
</body>
</html>

calling server side function/method jquery-ajax


How to Call server side C# asp.net code behind method/ function from client side code using ajax jquery/json js:

The below sample demonstrate how to call server side web method/function using jquery js not by javascript.

This sample code also shows how to call web method from asp.net button control (server side control) and HTML hyperlink anchor tag (client side control)

Sample ASPX source code:
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
   
    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
   
     <script type ="text/javascript">
         $(document).ready(function () {
            $('#<%=Button1.ClientID %>').click(function () {
                $.ajax({
                    type: "POST",
                    url: "serversidecallfromjs.aspx/callServerMethod",
                    data: "{}", /*indicates no parametre is passed to web method/function*/
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function (msg) {
                      $('#msgDiv').text(msg.d);
                   }
                })
               return false;
             });
       });

function callm()
{

 $.ajax({
                    type: "POST",
                    url: "serversidecallfromjs.aspx/callServerMethod1",
                    data: "{'parname': 100}" /*if any parametre is there means {'parname': 1}*/,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function (msg) {
                      $('#msgDiv').text(msg.d);
                   }
                })
                return false;
}

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Click" />
    <br />
    <a href="#" onclick="callm();">Click 2 clock</a>
    <br />
    <div id="msgDiv"></div>
    </div>
    </form>
</body>
</html>

Code behind:
 
using System.Web.Services;

namespace MyWebApps
{
    public partial class serversidecallfromjs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string callServerMethod()
        {
            return "Response from server.";
        }
        [WebMethod]
        public static string callServerMethod1(string parname)
        {
            return "Response from server" + parname + ".";
        }
      
    }
}
 

Wednesday, 18 April 2012

Create/Read global resource file code asp.net

How to Create/Read global resource file using asp.net code behind c#:

How to create Global resource file:

Steps:
1.Right click on web project and select Add --> Add ASP.Net Folder option
2.App_GlobalResources folder will be added.
3.Right click on "App_GlobalResources" folder and select Add --> Resource File --> give name  --> ok

example: 

readglobalresoircefile.resx  // global/default language
readglobalresoircefile.en-US.resx  // english language
readglobalresoircefile.fr-FR.resx  // french language
readglobalresoircefile.es-ES.resx  // spanish language

4.Add new key value. for example:
Key        value
------     ------
aa         English aa test
bb         English bb test


How to read/get Global resource file key value from code behind asp.net C#

Add the following Namespaces.

using System.Resources;
using System.Globalization;

Add the following code inside your custom function/method or in page load.

Source code sample:

ResourceManager rm = new System.Resources.ResourceManager("Resources.readglobalresoircefile", System.Reflection.Assembly.Load("App_GlobalResources"));
string ress = "en-US";  // to read us english resource.. if it is french then the culture code will be fr-FR likewise.
CultureInfo ci = new System.Globalization.CultureInfo(ress);
string resstring = rm.GetString("aa", ci);  // where aa indicates global resource file key value

we could assign this "resstring" string variable to any of asp.net control like textbox, label..

Monday, 9 April 2012

jquery for each loop to read elements

How to read elements by using for each loop in jquery ?

function(index, Element) -- A function to execute for each matched element.

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Example  1: Iterates through the array displaying each value text:

<script type="text/javascript">

var arrvar = [ "sample javascript code1", "sample javascript code2", "sample javascript code1", "sample javascript code1", "sample javascript code1" ];


    jQuery.each(arrvar, function() {
         alert(this);
      });

</script>

Example 2:Iterates over div elements /controls

      <div id="div1">jquery call 1</div>
      <div id="div2">javascript alert 1</div>
      <div id="div3">jquery call 2</div>
      <div id="div4">javascript alert 2</div>
      <div id="div5">jquery call 3</div>

<script type="text/javascript"> 

//$(document).click(function() { // onclick of body content call $(document).ready(function() {
 
      $("div").each(function () {
        alert($(this).text());
      });
    });

</script>

 

 

 

Sunday, 8 April 2012

Steps to create and reorder a tab in FAST search center SP 2010

How to create and reorder a tab in FAST search center Sharepoint 2010

Steps:

1.Open the SharePoint site.
2.Go to ->Site Actions->View all Contents
3.We have two lists namely – “Tabs in Search Pages” and “Tabs in Search Results” which controls the tab in Search page and Search results page respectivly.



4.Open the list “Tabs in Search Pages”.
5.Click on Item in the ribbon control present at the top of the page and select “New Item”.
6.A form appears. Provide the proper tab name. (eg:“Old Site”).
7.In the Page filed we need to enter the page name, this can be out-of-the box page name or create a new page and include it.
Follow the above steps for the other list also.





Steps to reorder the tabs displayed in the Search center

There is No UI for changing the order of the Tab that appears in Search Center. There is two work around available for this, But the below one would be the easiest one.
1.Open the SharePoint site.
2.Go to “Site Actions”->”View All Site Contents”
3.Select the list ”Tab in search page”
4.Click on “List” in the ribbon control present at the top of the page.
5.Select ”List Settings” present at the right hand corner of the tab that appears when clicked on “List”
6.In the URL change the “listedit.aspx” to “reorder.aspx”








7.Change the order and save it.
8.Still we have to make one more thing before we see the correct order in search center.
9.Go back to the list “Tabs in Search Pages” and edit any of the items (no changes required) just save it again to let SharePoint know that some modification is happen in the TAB.

Remove / delete list item using client object model (ecma script) in sp 2010

How to delete / remove list item using client object model (ecma script) in sharepoint 2010?
ECMAscript is a kind of javascript or jquery.

Sample code demo:


function deleteProduct(productId) {
var itemid= "1";
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle('listname');
    var itemToDelete = list.getItemById(itemid);
    itemToDelete.deleteObject();
    context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}

function success() {
    alert('success');
}
function failed(sender, args) {
    alert('failed. Message:' + args.get_message());
}

add new list item using client object model in sp 2010

How to add / create new list item using client object model (ecma script) in sharepoint 2010?

ECMAscript is a kind of javascript or jquery.

Sample code demo:

function addProduct() {
    try {
var itemname= "Mame 1";
var itemdesc="item desc1;";
        var context = new SP.ClientContext.get_current();       
        var web = context.get_web();
        var list = web.get_lists().getByTitle('listname');

        var listItemCreationInfo = new SP.ListItemCreationInformation();
        var newItem = list.addItem(listItemCreationInfo);
        newItem.set_item('ItemName', itemname);
        newItem.set_item('ItemDesc', itemdesc);
     
        newItem.update();
        context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
    }
    catch (e) {
        alert('error:' + e.Message);
    }
}

function success() {
    alert('success');
}
function failed(sender, args) {
    alert('failed. Message:' + args.get_message());
}

Friday, 6 April 2012

Get List and set list Items using Ecma script Client Object model using SharePoint 2010

How to Get List item and set list Items using Ecma script ( Client Object model) using SharePoint SP 2010 :

For my scenario, I have  to update the news count of news list ("NewsListName") based on the user viewed click count.
So, i have to get the current value of custom list item and update the same with the increment value of 1.

The following code will demonstrate how to get and update list item from client side script itself by using ecma script (client object model) in Sp 2010.

ecma script is a kind of java script which is used to update items without using any page postback / server side code in sharepoint 2010.

Sample code example:

source:

<a href="#" onclick="updatenewscount(newsid);">news title</a>

script:
 
<SharePoint:ScriptLink Name="SP.js" runat="server" LoadAfterUI="true" Localizable="false" />
-OR-
<script language="ecmascript" type="text/ecmascript" src="SP.js" />

<script language="ecmascript" type="text/ecmascript">
var newslist;
var web;
var context;
var newsid;
var newsitem;
var newscount = "Count";


function updatenewscount(itemId)
{
    newsid = itemId;

    context = new SP.ClientContext.get_current();
    web = context.get_web();
    newslist = web.get_lists().getByTitle("NewsListName");
    newsitem = newslist.getItemById(newsid);

    context.load(newslist);
    context.load(newsitem);
    context.executeQueryAsync(OnNewslistsLoaded);
}

function OnNewslistsLoaded()
{
    var currentcount = newsitem.get_item(newscount);

    newsitem.set_item(newscount, parseInt(currentcount)+1);
    newsitem.update();

    // Submit the query to the server
    context.load(newsitem);
    context.executeQueryAsync(OnNewsUpdated, OnError);   
}

function OnNewsUpdated (args)
{
     Alert(‘news count updated’);
}

function OnError(sender, args)
{
    alert(args.get_message());
}
</script>