Thursday 7 March 2013

How to get parent control id from child popup box in jquery with .net ?

Today I have got a case study in which I need to open a pop-up box on click of link from my asp.net web page and then I need to close that pop-up window after submit button get clicked.
   Isn't it very simple case and I am sure most of developers definetly gone through this situation once.If you google then you will see lots of ways available to do this.I did the same and found some of options in which only few worked for me which I want to share with you guys.
Ok, now lets dive into it.
My web page is using master page and for opening pop-up , I have used IFrame in <div> tag and for open this pop-up on button click I have used jquery code.

Pop-up window code on web page is :

1.<div id="divPopup"  class="popupReqCall">
2.        <div class="Close" style="display: none;">
3.            <img src="images/close.png" border="none" onclick="Close()"  alt="X" />
4.        </div>      
5.      <iframe id="ITestPopup" frameborder="0" scrolling="no" align="top"></iframe>
6.</div>

Here , line 1 is used as container of form control page (which contains textboxs and button) and line 2-4 is used as container of close button image with CSS and close() function which will fire on image click.Last but not the least, line 5 is used for holding user control page which will be add dynamically on click of link.

For getting id of parent <div> id and image control , I need to write jquery code which would be -
var frame = $('[id$=ITestPopup]', window.parent.document);
var imgClose = $('.Close', window.parent.document);

That's it !!
These are the key lines which we can use in any function which would be called on submit button click.
Noticiable part in this line is that first parameter is used as id of control,CSS class or any thing which represent that control and second parameter is defined that id of control is on called page i.e, parent page.
Hope this will help !! Happy Coding..


Tuesday 5 March 2013

How to fix header in repeater control in asp.net ?


Some time developers need a feature of fixed header to show thousands of data on the web pages.So, this tutorial will show how to fix header of control.Here, control can be repeater , gridview or any control which is using for showing data in asp.net.

For showing data , I am using repeater control and code will be like -

<asp:repeater id="Repeater1" runat="server">
  <HeaderTemplate>
     <table id="table12" width="505" style="table-layout: fixed; border:solid 1px black">
       <thead>
           <tr id="thead" style="width: 505px; background-color:#BEBEBE">
                <td>Name</td>
                <td>Mobile No</td>
                <td>Address</td>
            </tr>
        </thead>
  </HeaderTemplate>
  <ItemTemplate>
            <tr>
               <td>
                      <%#DataBinder.Eval(Container.DataItem, "Name")%>
               </td>
               <td>
                     <%#DataBinder.Eval(Container.DataItem,"MobileNo")%>
               </td>
                <td>
                      <%#DataBinder.Eval(Container.DataItem,"Address")%>
                </td>
            </tr>
   </ItemTemplate>
   <FooterTemplate>
      </table>
   </FooterTemplate>
 </asp:repeater>

In repeater control, I have design a HTML table which will be used for containing bind data.Thing which should be noticed here is style which is defined in <table> with id 'table12'.
In style , 'table-layout' property is fixed due to which the horizontal layout only depends on the table's width and the width of the columns, not the contents of the cells.
Now,give boundry to repeater control , so that,fixed header effect can be noticed.
<div style="overflow: scroll; height: 100px; width: 505px">
      <asp:repeater id="Repeater1" runat="server">
        ...............
      </asp:repeater>
</div>

Create another <div> tag which will hold header column names dynamically.
<div id="tableHeader">
</div>
Now finally the magic part, a javascript code -

function fixHeader()
{
   //get the id of table used in repeater control
   var t = document.getElementById("table12");
   var thead = t.getElementsByTagName("thead")[0];
   var t1 = t.cloneNode(false);
   t1.appendChild(thead);
   tableHeader.appendChild(t1)
}
       //call fixHeader() function on page load
        window.onload = fixHeader

put this code in <script> tag in <head> section of web page.
Output will be something like -

I hope that this tutorial will help you somewhere.
Happy Coding !!!



Monday 25 February 2013

How to flip text or image vertical on mouse over in CSS ?

This tutorial is about flip any text or image verticaly by using CSS class.
In .aspx page , write a <div> container in <body> tag which contains text which need to be flip.
Like -

<div>
    <!-- container would have your background image -->
    <h3> Hello There!</h3>
    <p> Here is some text</p>
</div>

after that , create CSS class which will do the magic of flip

<style type="text/css">

.flip-vertical :hover
{
    -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: flipv;
    filter: flipv;
 }

</style>

and use this class in <div> tag , so that text written in it will start flip on mouse over.
The complete code would be like :

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


<style type="text/css">

.flip-vertical :hover
{
    -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: flipv;
    filter: flipv;
 }

</style>
<body>
    <form id="form1" runat="server">
    <div class="flip-vertical">
        <!-- container would have your background image -->
        <h3>
            Hello There!</h3>
        <p>
            Here is some text</p>
    </div>
</form>
</body>
</html>

That's it !!! Copy this code and see the magic.
For flipping image, just change text part with any image and this CSS will do the same magic.
Note : This CSS is tested on Crome,Mozilla and IE 10.It's not supported by IE 9 or less version.
Output will be -


on mouse over text will be like -




Happy Coding ..


Monday 4 February 2013

How to get and set textbox value in jquery with asp.net

In this tutorial , I will explain how to get and set textbox value in jquery.
Firstly , add a latest reference of jquery library file in your page which you can either download from
http://www.jquery.com
or you can add CDN link like :
//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js.

Now, define one textbox control on page like :

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

For getting value of textbox in jquery, simply write :
$('#<textbox ID>').val();

like in above example :
$('#txtName').val();

For setting value of textbox control :
$('#txtName').val('Test');

That's it. Isn't it so simple !!! :-)

But one point I want to mention here that if you are using page in Master page, then it's possible that you will not be able to get and set control value like this because after rendering page, control id gets change like something 'ctl00$MainContent$Pending$txtName'.
So, by using $('#txtName') you will not get or set any thing.
    For getting id of textbox used in master page, you have to change code like :
$('[id$=txtName]').val();
here '$=' is basically used as one of attributes filter and syntax is :
[attribute$=value]
it matches elements that have the specified attribute and it ends with a certain value.



Friday 1 February 2013

How to create database driven role base menu in asp.net with c#


For my new task, I wanted to create role based menu where menu options will be change as per user role.
        The only condition was the first menu option 'Home' will remain same for all users with different page url. Like if user is admin then 'Home' link contain default admin page but if user is normal user then on the same 'Home' link default page will be show as per user need.

I have google and found many links but didn't get any role base menu link. So finally, with little trick and twist, I have created this menu which I wanted to share with you guys.

Firstly, create a method GetRolebaseMenuDetail(int UserID) to read data from database to dataset.For reading data , I have used stored procedure which return menu data.Pass User ID as parameter in stored procedure.

public DataSet GetRolebaseMenuDetail(int UserID)
        {

            DataSet dsTemp = new DataSet();
            DataRelation relation;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.Connection = conn;
                    comm.CommandText = "spMenuDetailsRoleWise";
                    comm.CommandType = CommandType.StoredProcedure;
                    comm.Parameters.AddWithValue("@UserID", UserID.ToString());
                    SqlDataAdapter da = new SqlDataAdapter(comm);
                    da.Fill(dsTemp);
                    da.Dispose();
                }
            }

            dsTemp.DataSetName = "Menus";
            dsTemp.Tables[0].TableName = "Menu";
            dsTemp.Tables[1].TableName = "RoleDetail";
 
   //set parent and child relationship between menu data
            relation = new DataRelation("ParentChild", dsTemp.Tables["Menu"].Columns["MenuID"], dsTemp.Tables["Menu"].Columns["ParentID"], false);
            relation.Nested = true;

            dsTemp.Relations.Add(relation);
            return dsTemp;
        }

After reading data in dataset , now bind Menu control

public void PopulateRolebaseMenu(int UserID,string HomePageURL)
        {
            DataSet dsMenu = GetRolebaseMenuDetail(UserID);
       
            foreach (DataRow masterRow in dsMenu.Tables["Menu"].Rows)
            {
                MenuItem masterItem = null;
                if (Convert.ToInt32(masterRow["ParentID"]) == 0)
                {
                    masterItem = new MenuItem((string)masterRow["Menu_Name"]);
                    masterItem.ToolTip = masterRow["Tooltip"].ToString();
                    if (masterRow["Menu_Name"].ToString() == "Home")
                    {
                        masterItem.NavigateUrl = HomePageURL;
                    }
                    else
                        masterItem.NavigateUrl = masterRow["URL"].ToString();
                    Menu1.Items.Add(masterItem);
                }

                foreach (DataRow childRow in masterRow.GetChildRows("ParentChild"))
                {
                    MenuItem childItem = new MenuItem((string)childRow["Menu_Name"]);
                    childItem.NavigateUrl = childRow["URL"].ToString();
                    childItem.ToolTip = childRow["Tooltip"].ToString();
                    masterItem.ChildItems.Add(childItem);
                }
            }      
        }


Here , first parameter is the User's Id who just login and second is the default page url which should be open on default 'Home' option , as per User role.
Happy Coding !!!! :-)




Wednesday 8 August 2012

How to add xml node in existing XML file ?


Let's say a XML file having format like :

XML file format :
-------------------------------
<?xml version="1.0" encoding="utf-8"?>
<items>
  <item id="1">
    <content>Get groceries</content>
    <status>false</status>
  </item>
  <item id="2">
    <content>Wash your car</content>
    <status>true</status>
  </item>  
</items>
Now we want to add new element in existing XML file. 

Add new Node to existing XML file:
-------------------------------------
 using System.Xml;
 using System.IO;
 
//call this method from page load
 private void AddNodeXML(string strFilePath)
 {
//get the existing xml file full path
 string XMLFile = Path.GetFullPath(strFilePath);

//create object of XML Document
 XmlDocument xDoc = new XmlDocument();
//load XML document from given URL
 xDoc.Load(XMLFile);

//get the root node in which you want to add new node
 XmlNode menu = xDoc.SelectSingleNode("//items");

//now,create new node with name,id and value
 XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, "item", null);
 XmlAttribute xa = xDoc.CreateAttribute("id");
 xa.Value = "3";
 newNode.Attributes.Append(xa);
//append new node as child node
 menu.AppendChild(newNode);

//create new element
 XmlNode newContent = xDoc.CreateElement("content");
 newContent.InnerText = "Clean Table";
 newNode.AppendChild(newContent);
 XmlNode newStatus = xDoc.CreateElement("status");
 newStatus.InnerText = "true";
//append new created element in node
 newNode.AppendChild(newStatus);
//save xml file 
 xDoc.Save(XMLFile);
 }



Monday 9 July 2012

How to create simple jquery tooltip in .net ?


This article will show how to create tooltip in .net based on jQuery and CSS.
For creating jquery tooltip, first you need to add reference of jQuery library :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>


Then after, on *.aspx , add <div> tag in <body> for containing tooltip text in hidden form :
<div class="tooltip" id="divPaid">
                        <asp:Label ID="lblTooltipText" runat="server" Text="This is just a sample text for showing tooltip content." ></asp:Label>  </div>

after that create <a> tag which will show tooltip on mouseover :
<a href='javascript:void(0)' id="lnkTip" onmouseover="simple_tooltip('lnkTip', 'tooltip','lblTooltipText');">

<img src="~/images/tooltip_blue.png" alt="" style="text-decoration: none;
                            border: 0px; height: 15px;" /></a>


now write simple CSS class which would be responsible for look of tooltip :
.tooltip
    {
        position: absolute;
        z-index: 999;
        left: -9999px;
        width: 250px;
        background-color: #62A2DA;
        padding: 5px;
        border: 1px solid #828282;
        font-family: Arial;
        font-size: 12px;
        color: #fff;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        border-top-right-radius: 5px;
        -moz-border-radius-bottomleft: 5px;
        -moz-border-radius-bottomright: 5px;
        -moz-border-radius-topright: 5px;
        -moz-border-radius-topleft: 5px;
    }
   
Finally , jQuery magic method :
function simple_tooltip(target_items, name, content) {
        var i = 0;
        var temp = "";
        temp = "<div class='" + name + "' id='" + target_items + i + "'><p>" + $("[id$=" + content + "]").text() + "</p></div>";
        $("body > div").remove();
        $("body").append(temp);

        var my_tooltip = $("[id$=" + target_items + i + "]");

        $('[id$=' + target_items + ']').mouseover(function () {
            my_tooltip.css({ display: "none" }).fadeIn(400);
        }).mousemove(function (kmouse) {
            my_tooltip.css({ left: kmouse.pageX + 15, top: kmouse.pageY + 15 });
        }).mouseout(function () {
            my_tooltip.fadeOut(400);
        });
    }


Here is output : 


Happy Coding !!!!

Friday 29 June 2012

Delegate and Events in C#

A delegate is a .NET class that encapsulates a method, but not in the same way other classes encapsulate methods. A delegate actually stores the address of a method that is contained in some other class. So, a delegate is really the equivalent of a function pointer in C++. However, they are also far more than that.

<from MSDN>
Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.


Declaring and using delegates 

You declare a delegate in a class or namespace using the delegate keyword and by specifying the signature of the method it will call. The following line declares a delegate named TestDelegate which will reference a method that returns void and accepts a string as the argument.

delegate void TestDelegate(string s);

Now that we have declared the TestDelegate, we can instantiate it to encapsulate a method of that signature.
 Then, we can invoke the method through the delegate, just as if we invoked the method itself. 
The next code sample creates an instance of TestDelegate and uses it to invoke the TestFun method.

class DelegateDemo {    
TestDelegate td = new TestDelegate(TestFun);
protected void Page_Load(object sender, EventArgs e) { td("Hello World"); } public void TestFun(string s) {
Console.WriteLine(s);
      }
}
Delegates only depend on the signature of the method, not on the class or object containing the method.
delegate can reference an instance method as well. The above example uses the TestDelegate to invoke an
method.

Events

One of the most common uses of delegates in .NET is event handling. Events are useful for notifying objects
of user interface events or state changes. The following example creates a Timer object that will fire an event
every second. The Timer class is defined in the System.Timers namespace.
class DelegateDemo {
   static void Main(string[] args) {
      Timer t = new Timer(1000);
      t.Elapsed += 
         new ElapsedEventHandler(Timer_Elapsed);
      t.Enabled = true;
      Console.WriteLine("Press enter to exit");
      Console.ReadLine();
      }
 
   static void Timer_Elapsed(object sender, ElapsedEventArgs e) {
      Console.WriteLine("tick");   
      }
   }
The Timer class contains the Elapsed event and fires it whenever its interval expires. In this example the 
Main method instantiates a Timer and registers an ElapsedEventHandler delegate with its Elapsed 
event. 

In this example, the method invoked by the ElapsedEventHandler delegate is the Timer_Elapsed 
method. Following the convention of all event handling delegates, the ElapsedEventHandler delegate 
returns void and accepts two parameters. The first is a reference to the object that signaled the event and 
the second is a argument derived of EventArgs which stores pertinent information about the event.

Monday 11 June 2012

How to post form data from HTML to ASP.Net page

For sending form data from HTML page to ASP.Net page ,


In HTML page , do the method type as POST and action should be full path of .aspx page.Like
Test.html page
<html>
<body>
 <form id="form1" action="../MailerTest.aspx" method="post"> 

     <input type="text" name="txtName" id="Name" />
    <br/>
    <input type="text" name="txtEmail" id="Email" />
    <br/>
  <input type="submit" name="btnPost" value="Submit" id="btnPost" />
</form>
</body>
</html> 


Default.aspx page
On aspx page , get html controls data on page_load event as
strName = Request.Form["txtName"].ToString();
strEmail = Request.Form["txtEmail"].ToString();


Thing which we need to take care of that Key value in Request.Form should be name
in <input> tag besides of id.After clicking on 'Submit' button HTML page will post data to
aspx page.

Difference between live() and delegate() in jQuery


.live() requires you run the selector immediately, unless you're using the result it's very wasteful. The event handler here is attached to document, so all event of that type from any elements bubbling must be checked. Here's a usage example:

$(".myClass").live("click", function() { alert("Hello World"); }); 

 Note that the statement $(".myClass") ran that selector to find all elements with that class even though we don't care about them, all we wanted was the string ".myClass" to match later when click events bubble up to document.

.delegate() actually uses .live() internally, but with a context. The selector is not run immediately, so it's more efficient already, and it doesn't attach to document (though it can) it's much more local...and all those other events from other element trees you don't care about are never even checked when bubbled...again more efficient. Here's a usage example:
$("#table").delegate("td", "click", function() { alert("Hello World"); }); 

 Now what happened here? We ran $("#table") to get the element to attach to ,admittedly more expensive than document, but we're using the result). Then we attach an event handler to that (or those in other cases) elements. Only clicks from within that element are checked against the "td" selector when they happen, not from everywhere like .live() does (since everything is inside document).