Monday, April 16, 2018

Change Browser URL without reloading (refreshing) page using HTML5 in JavaScript and jQuery

n this short article I will explain how to change the URL in browser without reloading or refreshing the page using HTML5 History API in JavaScript and jQuery.
HTML5 History API allows browsers to modify the URL without reloading or refreshing the page using pushState function.
HTML5 History pushState method
The pushState method works similar to window.location but it does not refresh or reload the page and it will modify the URL even if the page does not exists. The pushState method actually inserts an entry into the history of the browsers which allows us to go back and forth using the browser’s forward and back buttons.
The pushState method accepts the following three parameters.
1. State object: - The state object is a JavaScript object which can contain any details about the page and must be serializable.
2. Title: - The title of the page.
3. URL – The URL of the page.
Change Browser URL without reloading using JavaScript
The HTML Markup consists of 3 buttons which make a call to a function ChangeUrl. This function accepts the page Title and URL as parameters.
It first checks whether browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
<script type="text/javascript">
function ChangeUrl(title, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Title: title, Url: url };
        history.pushState(obj, obj.Title, obj.Url);
    } else {
        alert("Browser does not support HTML5.");
    }
}
</script>
<input type="button" value="Page1" onclick="ChangeUrl('Page1', 'Page1.htm');" />
<input type="button" value="Page2" onclick="ChangeUrl('Page2', 'Page2.htm');" />
<input type="button" value="Page3" onclick="ChangeUrl('Page3', 'Page3.htm');" />
Change Browser URL without reloading using jQuery
The HTML Markup consists of 3 buttons to which the jQuery click event handler has been assigned. Inside the jQuery click event handler, a function ChangeUrl is being called which accepts the page Title and URL as parameters.
This function first checks whether browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function ChangeUrl(page, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = { Page: page, Url: url };
            history.pushState(obj, obj.Page, obj.Url);
        } else {
            alert("Browser does not support HTML5.");
        }
    }
    $(function () {
        $("#button1").click(function () {
            ChangeUrl('Page1''Page1.htm');
        });
        $("#button2").click(function () {
            ChangeUrl('Page2''Page2.htm');
        });
        $("#button3").click(function () {
            ChangeUrl('Page3''Page3.htm');
        });
    });
</script>
<input type="button" value="Page1" id="button1" />
<input type="button" value="Page2" id="button2" />
<input type="button" value="Page3" id="button3" />

source : https://www.aspsnippets.com/Articles/Change-Browser-URL-without-reloading-refreshing-page-using-HTML5-in-JavaScript-and-jQuery.aspx

Friday, April 13, 2018

Easily Add/Remove CSS classes on a HTML Server Side Control

Today I needed to add a CSS class to a html element from the code behind on the server.  The html element already had one CSS class but I needed to add and remove another CSS class as needed (I wanted to add and remove an error class when a text box had an invalid value).  I figured there was some built in ability to do this in asp.net already but I was wrong.  The current support for changing the CSS class attribute from the server looks like this:
 
HtmlGenericControl myControl = new HtmlGenericControl();
myControl.Attributes["class"] = "MyCSSClassName";
The problem is doing this will overwrite any existing CSS classes that were set in the markup directly.  The solution is not hard, you just need to do this:
 
HtmlGenericControl myControl = new HtmlGenericControl();
myControl.Attributes["class"] = "MyCSSClassName MyCSSErrorClassName";
The string set in the “class” attribute just needs to follow the standard CSS format for multiple classes on a single element.  Updating that string every time I needed to add or remove a class would get old quick so I decided to use an extension method to make life easier.  Actually I created three methods:  CSSAddClass, CSSHasClass, and CSSRemoveClass.  Using these methods you can easily add and remove my CSS error class as needed.  Here is the code for my extension methods:
 
public static class HTMLExtensions
    {
        public static void CSSAddClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (string.IsNullOrEmpty(classes))
            {
                ctrl.Attributes["class"] = className;
            }
            else
            {
                var classList = classes.Trim().Split(' ').ToList();
                if (!classList.Contains(className))
                {
                    classList.Add(className);
                    ctrl.Attributes["class"] = classList.Aggregate((current, next) => string.Format("{0} {1}", current, next));
                }
            }
        }

        public static bool CSSHasClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (string.IsNullOrEmpty(classes))
            {
                return false;
            }
            else
            {
                var classList = classes.Trim().Split(' ').ToList();
                return classList.Contains(className);
            }
        }

        public static void CSSRemoveClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (!string.IsNullOrEmpty(classes))
            {
                var classList = classes.Trim().Split(' ').ToList();
                if (!classList.Contains(className))
                {
                    classList.Remove(className);
                    ctrl.Attributes["class"] = classList.Aggregate((current, next) => string.Format("{0} {1}", current, next));
                }
            }
        }
    }
 
From my code behind I can now just write code like this when I need to change the CSS class of an element:
 
this.labTest.CSSAddClass("MyCSSErrorClassName");
 
The extension code is extending html generic control only because that is what I needed it for but you can easily change it to work with other web controls that have the attributes property.

Source : http://www.frankwisniewski.net/2013/04/17/easily-addremove-css-classes-on-a-html-server-side-control/

Thursday, April 5, 2018

Selecting GridView Row by clicking anywhere on the Row

In this article I will explain how to select GridView Row when mouse is clicked anywhere on the GridView Row in ASP.Net.

HTML Markup
The HTML Markup consists of an ASP.Net GridView with two columns and a Dummy LinkButton. The Dummy LinkButton is used, so that the ASP.Net __doPostBack JavaScript function is rendered as we will require it for Row Selection.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound" OnSelectedIndexChanged = "OnSelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
<asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
Namespaces
You will need to import the following namespaces
C#
using System.Data;
using System.Drawing;
VB.Net
Imports System.Data
Imports System.Drawing
Binding the GridView
The GridView is populated using some dummy records using DataTable.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "John Hammond""United States");
        dt.Rows.Add(2, "Mudassar Khan""India");
        dt.Rows.Add(3, "Suzanne Mathews""France");
        dt.Rows.Add(4, "Robert Schidner""Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "John Hammond""United States")
        dt.Rows.Add(2, "Mudassar Khan""India")
        dt.Rows.Add(3, "Suzanne Mathews""France")
        dt.Rows.Add(4, "Robert Schidner""Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
Select GridView Row on mouse click event in ASP.Net
In the OnRowDataBound event handler, for each GridView Row a JavaScript click event handler is attached using the onclick attribute. The GetPostBackClientHyperlink method accepts the GridView instance as well as the command with the Row Index of the Row.
Note: GetPostBackClientHyperlink when rendered this gets converted to the JavaScript __doPostBack method that we were discussing earlier.
Doing the above makes each GridView Row clickable and also it executes the OnSelectedIndexChanged event handler (discussed below) when clicked.
C#
protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
        e.Row.ToolTip = "Click to select this row.";
    }
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Attributes("onclick") = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" & e.Row.RowIndex)
        e.Row.ToolTip = "Click to select this row."
    End If
End Sub
The OnSelectedIndexChanged event handler
Below is the OnSelectedIndexChanged event handler which will be triggered when the GridView Row is clicked. When any GridView row is clicked the background color of the Selected GridView Row is changed using the following code, to know more about it please refer my article How to change GridView Selected Row Color in ASP.Net
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowIndex == GridView1.SelectedIndex)
        {
            row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
            row.ToolTip = string.Empty;
        }
        else
        {
            row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
            row.ToolTip = "Click to select this row.";
        }
    }
}
VB.Net
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
    For Each row As GridViewRow In GridView1.Rows
        If row.RowIndex = GridView1.SelectedIndex Then
            row.BackColor = ColorTranslator.FromHtml("#A1DCF2")
            row.ToolTip = String.Empty
        Else
            row.BackColor = ColorTranslator.FromHtml("#FFFFFF")
            row.ToolTip = "Click to select this row."
        End If
    Next
End Sub
  
 
Handling the Event Validation Error
Since we are attaching the event directly to the GridView Row which by default does not have any OnClick event, you might land into the following error.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
To resolve the above error you must set the property EnableEventValidation = "false"
in the @Page Directive as shown below

source : https://www.aspsnippets.com/Articles/Selecting-GridView-Row-by-clicking-anywhere-on-the-Row.aspx

Monday, April 2, 2018

__doPostBack function

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.
Hi everyone.
Today I am going to talk about the __doPostBack function, because there is some confusion with using this function.
You can see this __doPostBack function in your ASP.NET generated HTML code.
The function takes the following two arguments: 
eventTarget  - This contains the ID of the control that caused the post back.
eventArgument
 - This contains any additional data associated with the control.
In any ASP.NET page the two hidden fields: __EVENTTARGET and __EVENTARGUMENT are automatically declared.When a page is posted back to the server ASP.NET inspects __EVENTTARGET and __EVENTARGUMENT values and this way it can decide which of the controls caused the page to be posted back and what is the event that has to be handled.
The value of the parameters eventTarget and eventArgument are stored in the hidden fields. The two hidden variables can be accessed from the code behind using the forms or params collection.
If we inspect the code of the <span class="Apple-style-span">__doPostBack</span> function, we can see that it first sets the values of two hidden fields with the two parameters passed to the function. After this, the page is submitted back to the server. The ID of the control which causes the postback is stored in the __EVENTTARGET hidden field, so you can find the control which caused the postback.
<a id="LinkButton1" href="javascript:__doPostBack( 'LButton3','' )">LinkButton</a>
You can see the function call __doPostBack('LButton3','') in the href and the argument passed for eventTarget is "LButton3" which is the id of the link button control (EventSource)

Example

  1. Add two hidden fields inside the form.
    <input type =hidden name ="__EVENTTARGET" value ="">
    <input type =hidden name ="__EVENTARGUMENT" value =""> 
  2. Add javascript under the Head tag.
    <script>
    function __doPostBack( eventTarget, eventArgument )
    {
        document.Form1.__EVENTTARGET.value = eventTarget;
        document.Form1.__EVENTARGUMENT.value = eventArgument;
        document.Form1.submit();
    }
    </script>  
  3. Add two controls.
    <a id="LButton3" href="javascript:__doPostBack('Button2','')">LinkButton</a>
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
  4. Add function in your cs page.
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Write("Welcome to  Student Academic Blog");
    }
  5. You also need some code in the code behind to capture the postback and fire the event. In the PageLoad method add.
    if (Request.Form["__EVENTTARGET"] == "Button2")
    {
        // Fire event
        Button2_Click( this, new EventArgs( ) );
    }
    This will capture the posted variable __EVENTTARGET and cause it to fire the event "Button2_Click". You can also pass an event argument along with the target in case you need to pass something to your code behind:
    __doPostBack( "Button2', '<event argument here>' ) 
    This would be captured in the code behind as Request.Form["__EVENTARGUEMENT"]
So this is how you can use __doPostBack
Enjoy it

source : https://www.codeproject.com/Articles/667531/doPostBack-function