Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, 23 September 2009

Get URL Querystring Parameters using Javascript

As we know in ASP.net we can use Request.QueryString["variableName"] to retrieve the values of the variables in the HTTP query string. However if we need to get the parameter value in the client script, for instance we want to have an alert window to display a parameter value is not as straight forward as we do in server-side programming. Use the gup() helper function in JavaScript below can help us with this

function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}

The way that the function is used is fairly simple. Let's say you have the following URL:

http://localhost/script/directory/NAMES.ASP?name=Fred&id=123

You want to get the value from the frank parameter so you call the javascript function as follows:

var name_param = gup( 'name' );

Thursday, 13 August 2009

Create a master and detail relationship report in ASP.net

A very common requirement I received from customers is to display a summary report in the main page, while user click on each row of the grid view, a new window will popup and show the detail information of the selected row. One scenario is that we have a list of customer orders in the main page, when user click on each order inside the gridview, a window will popup to show the order details.

We can easily achieve this in .net with a little bit JavaScript, the technique we discussed in my previous post Calling a JavaScript function from server side code. In today’s demo I am going to use Orders and Order Details tables from Northwind database. Let’s start.

1. Create our main page orders.asp. In the design view, drag a data source and select all from table orders.





2. In the source view, add 2 JavaScript functions after the body tag. The first function is to highlight the row on mouse hover. The second function is to open a popup window and pass the order no parameter OrderID to the second page orderdtl.asp which I am going to create in step 4.



3. Create a RowDataBound event handler as below.




protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onmouseover"] = "highlight(this, true);this.style.cursor = 'pointer'";
e.Row.Attributes["onmouseout"] = "highlight(this, false);";

e.Row.Attributes["onclick"] = "PopUpWin(this, 'OrderDtl.aspx', 'name',150,200,410,315)";
}

4. Create a new webpage called orderdtl.asp.
5. In the page design view, drag a GridView on to the page and configure the data source selecting from Order Details



In where clause, set the parameter value from Request.QueryString(“OrdrID”).



6. Save all and run the page. If everything works well, you should see the result as:

Friday, 24 July 2009

How to highlight a GridView's row on mouse hover in ASP.net?

With small amount of JavaScript we can correctly highlight the GridView row when user hovers over each row. This can be very helpful when we have a very wide report. To achieve this, we can use the technique I discussed in the previous article: Calling a JavaScript function from server side code.

The following JavaScript can do the trick, please note this also works well if you have set the AlternatingRowStyle of the GridView.

function highlight(tableRow, active) {
if (active) {
tableRow.originalstyle = tableRow.style.backgroundColor;
tableRow.style.backgroundColor = '#cfc';
}
else {
tableRow.style.backgroundColor = tableRow.originalstyle;
}
}

Now we can drag a GridView to the page and selected a valid data source. In this demo, I use the Order table in Northwind database. In order to highlight the row on mouse hover, we need to add some custom JavaScript code to onmouseover and onmouseout event handlers of the rows of our GridView. In codehind we have:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onmouseover"] = "highlight(this, true);this.style.cursor = 'pointer'";
e.Row.Attributes["onmouseout"] = "highlight(this, false);";
}

Run the application, you will see the result as the screenshot below:

How to call a Server Side Function from Client Side Code using JavaScript in ASP.net Ajax

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. ASP.Net AJAX introduced a technique called PageMethods using which we can call server side methods from JavaScript. Try to imagine a scenario, in a user registration form, when user type a user name in a textbox, a server side process is triggered to find whether this is an exiting user or not in our user table in the database. In this example I am using the SQL Server 2005 as backend.

1.Create a demo table on Northwind db and insert 3 users into the table.

CREATE TABLE demo(user_id varchar(10) PRIMARY KEY);
insert into demo values ('user1');
insert into demo values ('user2');
insert into demo values ('user3');

2.Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag. Let’s create a simple function as below:

[System.Web.Services.WebMethod]
public static bool IsUserExist(string strUserID)
{
bool blUserExist = false;
string connectionString = "Data Source=localhost;Initial Catalog=Northwind; " +
"Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string strSqlStatement = "select * from demo where user_id = '" + strUserID + "'";
SqlCommand cmd = new SqlCommand(strSqlStatement, conn);
SqlDataReader reader = cmd.ExecuteReader();

if (reader.HasRows)
blUserExist = true;

reader.Close();
conn.Close();

return blUserExist;
}

3. Go to the Markup page and drag a ScriptManager to the page. The “EnablePageMethods” attribute has to be added on the ScriptManager tag and set it to “true”.




4. Adding a simple HTML TextBox as:



5. Adding the JavaScript code as below:



The “OnSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnFailure” will be called if an exception is thrown.

6. Running the application. Will see the screenshot as below:

Tuesday, 21 July 2009

Ways to call JavaScript function from C# in ASP.net

As we all know in ASP.net framework, C# code executes on the server whereas JavaScript code executes in the client's browser. We can't actually "access" JavaScript from the server-side. All that we can do is write the JavaScript function call into the markup and have it execute when all server-side processing is completed and the page renders to the browser.

There are number of workarounds we can achieve this. To demonstrate let us declare a JavaScript Function in the markup page first.



Now we need to decide how we are going to execute this function in our code page.

1. We want to call the function on a page_load event, then we can put the code below to the page_load method:

protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "alertMe();", true);
}
}

2. We want to call the function on a buttion click event, we can write the code as:

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "alertMe()");
}

Or

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes["onclick"] = "alertMe()";
}

3. If we have a GridView and we want to call the method when the GridView Row get clicked by the user. This can be very useful in master-detail relationship data. For example, we have a summary GridView report shows customer order headers, when user click on the row, a small window will popup to show the details of the selected order. To do this, we simply add the following line to the GridView RowDataBound event:

GridView1.Attributes["onclick"] = "alertMe()";