ASP.NET Repeater with jQuery Dialog Popup : Reading Data from a WebMethod

ASP.NET Repeater with jQuery Popup with WebMethod

ASP.NET Repeater with jQuery Popup with WebMethod

Introduction

This blog will take you through the steps to call a simple WebMethod to get the details of one record shown on a Repeater and show the retrieved details on jQuery Dialog popup.

Background

This can be considered as a second part of the article series where I am dealing with Repeaters and Dialogs. The first part was – ASP.NET Repeater with jQuery Dialog Popup.

Walk Through

First of all, follow all the steps as described on the previous article I mentioned above to design the Repeater and bind data to it. You can also download the project and start coding on that. After you are done with it, you will find one jQuery code which is called on the Image Button Click. Inside this event, we are trying to get the row which is clicked and finding all the values of that row so that we can display on the jQuery Popup.

// ImageButton Click Event.
$('#tblEmployeeDetails .imgButton').click(function () {
	// Get the Current Row and its values.
	var currentRow = $(this).parents("tr");
	var empId = currentRow.find("span[id*='lblEmployeeId']").text();
	var empName = currentRow.find("span[id*='lblName']").text();
	var empLocation = currentRow.find("span[id*='lblLocation']").text();

	// Populate labels inside the dailog.
	$("#lblEmpId").text(empId);
	$("#lblEmpName").text(empName);
	$("#lblEmpLocation").text(empLocation);

	// Open the dialog.
	$("#popupdiv").dialog({
		title: "Details of <em>" + empName + "</em>",
		width: 430,
		height: 240,
		modal: true,
		buttons: {
			Close: function () {
				$(this).dialog('close');
			}
		}
	});

	return false;
});

What’s Next?

We will now remove the highlighted lines above and try to get these values from server by calling a WebMethod. We will also fetch another extra thing about the employee that is “Biography”.

When a method is decorated with [WebMethod] attribute, that is actually exposed as a XML Web Service. Read more (on how to deal with WebMethods in jQuery) here.

Alright, let’s alter our code a bit to call our WebMethod.

// ImageButton Click Event.
$('#tblEmployeeDetails .imgButton').click(function () {
	// Get the Current Row and its values.
	var currentRow = $(this).parents("tr");
	var empId = currentRow.find("span[id*='lblEmployeeId']").text();
        $("#lblEmpId").text(empId);

	$.ajax({
		url: 'RepeaterWithjQueryPopup.aspx/GetEmployeeDetails',
		data: '{ employeeId: ' + empId + '  }',
		type: 'POST',
		contentType: "application/json; charset=utf-8",
		dataType: 'json',
		success: function (result) {
			if (result.d.length > 0) {
				var employee = $.parseJSON(result.d);

				// Populate labels inside the dailog.
				$("#lblEmpName").text(employee.Name);
				$("#lblEmpLocation").text(employee.Location);
				$("#lblEmpBiography").text(employee.Biography);

				// Open the dialog.
				$("#popupdiv").dialog({
					title: "Details of <em>" + employee.Name + "</em>",
					width: 430,
					height: 270,
					modal: true,
					buttons: {
						Close: function () {
							$(this).dialog('close');
						}
					}
				});
			}
		},
		error: function (xhr) {
			alert('error');
		}
	});

	return false;
});

url: ‘RepeaterWithjQueryPopup.aspx/GetEmployeeDetails’

Indicates the URL of the WebMethod, which is “RepeaterWithjQueryPopup.aspx/GetEmployeeDetails“. This is in the format {PageName/WebMethodName}.

data: ‘{ employeeId: ‘ + empId + ‘ }’

Indicates that we are passing the employee id of the row which is clicked. This will help us to get the record of this particular employee.

In Success Method

When WebMethod returns the result in form of a object, we parse it and then we just read the properties and assign it to the labels inside the popup. For parsing, I have used jQuery.parseJSON(), which converts the object to a JSON object so that we can read it very easily.

var employee = $.parseJSON(result.d);

$("#lblEmpName").text(employee.Name);
$("#lblEmpLocation").text(employee.Location);
$("#lblEmpBiography").text(employee.Biography);

Have a look on the WebMethod Code

[WebMethod]
public static string GetEmployeeDetails(string employeeId)
{
	DataTable dtEmployees = GetAllEmployees();
	DataRow[] employeeRow = dtEmployees.Select("EmployeeId = " + employeeId);

	if (employeeRow.Length > 0)
	{
		var row = new Dictionary<string, string>
		{
			{"Name", employeeRow[0]["Name"].ToString()},
			{"Location", employeeRow[0]["Location"].ToString()},
			{"Biography", employeeRow[0]["Biography"].ToString()}
		};

		var serializer = new JavaScriptSerializer();

		return serializer.Serialize(row);
	}

	return string.Empty;
}

First of all we are getting all employees and then filtering out the employee which is needed by the employeeId, which is passed from the client side Ajax call. Then we are making a dictionary object with the property name and value. After this, this is just a matter of serializing it with the help of JavaScriptSerializer and send it back to client to parse and operate on it.

Your Views

Feel free to download the project and play on top of it. Should you have any queries, do let me know by commenting below. Let’s interact and code!!! Share among your friends, if you like it.

Advertisements

ASP.NET Repeater with jQuery Dialog Popup

ASP.NET Repeater with jQuery Dialog Popup

ASP.NET Repeater with jQuery Dialog Popup

Introduction

This blog will take you through the steps to create a ASP.NET Repeater and show the details of a particular row on jQuery Dialog popup.

Background

I was quite a bit into the Repeater control, when I wrote ASP.NET Repeater with jQuery Slider. It is a very useful control to repeat items with well formatted HTML designs. While going through forums, I found members asking questions on opening a popup from the Repeater Row and show details inside that. So, I thought of implementing this with jQuery UI Dialog. Later I will come up with other techniques to do this task.

Let’s Start !!!

Step-1 : Add ASP.NET Repeater Control on aspx Page

We will show the following details for some demo Employees on Repeater.

  1. Employee Id
  2. Name
  3. Location

Let’s see how the design will look like. I will explain different parts of the ASP.NET Repeater.

HeaderTemplate

So, inside the HeaderTemplate, I have defined the table and the header rows with Column Names.

<HeaderTemplate>
	<table id="tblEmployeeDetails" 
         style="border: 1px solid; margin-left: auto; margin-right: auto;">
		<tr>
			<th>
				Employee Id
			</th>
			<th>
				Name
			</th>
			<th>
				Location
			</th>
			<th>
				Pop
			</th>
		</tr>
</HeaderTemplate>

ItemTemplate

Then in ItemTemplate, the data rows are defined with proper Label Tags to hold the column values inside table data (td). The labels are getting values by Eval expressions.

For instance - Text='<%# Eval("EmployeeId") %>' binds the EmployeeId to the Label's Text..
<ItemTemplate>
	<tr>
		<td bgcolor="#CCFFCC">
			<asp:Label runat="server" ID="lblEmployeeId" Text='<%# Eval("EmployeeId") %>' />
		</td>
		<td bgcolor="#CCFFCC">
			<asp:Label runat="server" ID="lblName" Text='<%# Eval("Name") %>' />
		</td>
		<td bgcolor="#CCFFCC">
			<asp:Label runat="server" ID="lblLocation" Text='<%# Eval("Location") %>' />
		</td>
		<td bgcolor="#CCFFCC">
			<asp:ImageButton ID="imbShowDetails" class="imgButton" Height="50" 
                             runat="server" ImageUrl="images/popup.png" />
		</td>
	</tr>
</ItemTemplate>

AlternatingItemTemplate

AlternatingItemTemplate is used so that alternate rows can be displayed differently. The same columns are copied but doesn’t have bgcolor added to them.

<AlternatingItemTemplate>
	<tr>
		<td>
			<asp:Label runat="server" ID="lblEmployeeId" Text='<%# Eval("EmployeeId") %>' />
		</td>
		<td>
			<asp:Label runat="server" ID="lblName" Text='<%# Eval("Name") %>' />
		</td>
		<td>
			<asp:Label runat="server" ID="lblLocation" Text='<%# Eval("Location") %>' />
		</td>
		<td bgcolor="#CCFFCC">
			<asp:ImageButton ID="imbShowDetails" class="imgButton" Height="50" 
                             runat="server" ImageUrl="images/popup.png" />
		</td>
	</tr>
</AlternatingItemTemplate>

FooterTemplate

Last, but not the least, inside FooterTemplate we will close the table.

<FooterTemplate>
	</table>
</FooterTemplate>

For the whole code, download the project from the link given at the top of this blog post.

Step-2 : Bind Repeater from Code Behind

Pretty simple. Inside BindEmployees(), we are just creating a DataTable with required columns and adding some demo records.

protected void Page_Load(object sender, EventArgs e)
{
	if (!IsPostBack)
	{
		BindEmployees();
	}
}

private void BindEmployees()
{
	// Create DataTable and add Columns.
	DataTable dtEmployees = new DataTable();
	dtEmployees.Columns.Add("Name", typeof(string));
	dtEmployees.Columns.Add("EmployeeId", typeof(int));
	dtEmployees.Columns.Add("Location", typeof(string));

	// Add demo Rows.
	dtEmployees.Rows.Add("Nirmal Hota", 1, "Bhubaneswar");
	dtEmployees.Rows.Add("Debasis Behera", 2, "Bengaluru");
	dtEmployees.Rows.Add("Sujeet Singh", 3, "New Delhi");
	dtEmployees.Rows.Add("Ashutosh Sahu", 4, "Mangalore");
	dtEmployees.Rows.Add("Kabi Sahoo", 5, "Gurgaon");

	// Bind the Repeater.
	rptEmployees.DataSource = dtEmployees;
	rptEmployees.DataBind();
}

Step-3 : Design the Dialog Popup Div

We will design a very simple table to show the details of a particular row on ImageButton Click Event. Below is the HTML of the popup div.

<div id="popupdiv" style="display: none">
	<table>
		<tbody>
			<tr>
				<td>
					<label class="label">
						Employee Id:</label>
				</td>
				<td>
					<label id="lblEmpId">
					</label>
				</td>
			</tr>
			<tr>
				<td>
					<label class="label">
						Name:</label>
				</td>
				<td>
					<label id="lblEmpName">
					</label>
				</td>
			</tr>
			<tr>
				<td>
					<label class="label">
						Location:</label>
				</td>
				<td>
					<label id="lblEmpLocation">
					</label>
				</td>
			</tr>
		</tbody>
	</table>
</div>

NOTE : The highlighted labels will be populated with the row values when you click the popup image. We will explore more on this in the next step.

Step-4 : Define ImageButton Click Event for the Dialog

Prerequisites

Going further, we will be adding jQuery codes. So, we need jQuery reference. As we will deal with jQuery Dialog, we also need jQueryUI reference. Below is the references we need to add to our page.

<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Now we are ready for the click event of ImageButton. Let’s start writing.

Define Click Event for all ImageButtons

First of all, we need to attach click events for all the ImageButtons rendered on Repeater rows. To do that, we will select all the ImageButtons having a common class .imgButton inside the Employees Table that is tblEmployeeDetails. So, the selector will be…

$('#tblEmployeeDetails .imgButton')

This will select all the ImageButtons inside the Employees table.
Now, attach click event to it as given below.

$('#tblEmployeeDetails .imgButton').click(function () {
    // We will write all logic here.
});

Get the Current Row where Image is clicked

See the picture below which shows the rendered HTML for the Repeater.

Repeater HTML Rendered on Browser

Repeater HTML Rendered on Browser


So, let’s get the parent “tr” of the ImageButton first so that later we can access all the values inside it as shown above. To get the parent tr, we will use .parents with selector “tr”. See code below.

$('#tblEmployeeDetails .imgButton').click(function () {
    // Get the Current Row.
    var currentRow = $(this).parents("tr");
});

Find the Row Values

Now this is very easy. We just need to find the values by the id of labels. I have use .find with proper selector. The selector is formed with the help of Attribute Contains Selector [name*=”value”]. That is because

$('#tblEmployeeDetails .imgButton').click(function () {
	// Get the Current Row and its values.
	var currentRow = $(this).parents("tr");
	var empId = currentRow.find("span[id*='lblEmployeeId']").text();
	var empName = currentRow.find("span[id*='lblName']").text();
	var empLocation = currentRow.find("span[id*='lblLocation']").text();
});

Open the Dialog

Just need to call jQuery dialog Event for the div popupdiv.

// ImageButton Click Event.
$('#tblEmployeeDetails .imgButton').click(function () {
	// Get the Current Row and its values.
	var currentRow = $(this).parents("tr");
	var empId = currentRow.find("span[id*='lblEmployeeId']").text();
	var empName = currentRow.find("span[id*='lblName']").text();
	var empLocation = currentRow.find("span[id*='lblLocation']").text();

	// Populate labels inside the dailog.
	$("#lblEmpId").text(empId);
	$("#lblEmpName").text(empName);
	$("#lblEmpLocation").text(empLocation);

	// Open the dialog.
	$("#popupdiv").dialog({
		title: "Details of <em>" + empName + "</em>",
		width: 430,
		height: 240,
		modal: true,
		buttons: {
			Close: function () {
				$(this).dialog('close');
			}
		}
	});

	return false;
});

Notes

  1. Line 16: Here to make the empName italics I have assigned em tags. But HTML tags are not supported in dialog title. To support that, I have added one prototype as given below, which will just assign the title text to the title html.
    // Prototype to assign HTML to the dialog title bar.
    $.widget('ui.dialog', jQuery.extend({}, jQuery.ui.dialog.prototype, {
    	_title: function (titleBar) {
    		titleBar.html(this.options.title || ' ');
    	}
    }));
    
  2. Line 27: We are returning false, otherwise page will post back and the modal will play hide and seek. 🙂

Conclusion

Uff !!! So much code. Let me know, if you liked the blog or not. Should you have any questions or need any help, please feel free to add a comment below or contact me. I will reply and together we will resolve issues.

Don’t forget to share this post with your friends and colleagues. You just need to click share buttons displayed below.

Happy coding !!! 🙂

ASP.NET Repeater with jQuery Slider

Image Slider with Repeater

Image Slider with Repeater


In this Blog, we will learn how to integrate one jQuery Slider Plugin with the ASP.NET Repeater Control.

Background

There was a question on implementation of slider with ASP.NET DataList Control and the guy who posted that was facing issues. The issue was actually due to the DataList control, which was rendering as HTML tables breaking the default jQuery Slider functionality. After researching a bit, I found that, it is very easy to implement this with the ASP.NET Repeater control. Let’s go step by step and learn.

Step by Step

Step-1 : Download jQuery Slider Plugin

You can take any jQuery Slider, but you need to see how exactly it allows contents inside it. For this example, we will be using the Elastislide. Hit the “Download Source” button on the page to download the zip file containing the Plugin files. We will try to implement the demo given here (Example 1).

Let’s extract the zip file. You will have something like this inside the Extracted folder.

Extracted jQuery Slider Files

Extracted jQuery Slider Files


So, here we can find all related JavaScript, CSS and images used for the Demos. The demo, which we will implement with Repeater is shown inside the index.html (highlighted in image). You can directly run and see in browser.

Step-2 : Analysis of Demo HTML Page

JavaScript and CSS Files Included

In Head section…

<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/elastislide.css" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
<script src="js/modernizr.custom.17475.js"></script>

In Body Section…

<script type="text/javascript" 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript" src="js/jquerypp.custom.js"></script>
<script type="text/javascript" src="js/jquery.elastislide.js"></script>

So, we will also include these files in our aspx page.

HTML Markup for Image Slider

If you open and see the index.html page, you will find a HTML structure which loads all the images. (I have removed the not needed headers and other HTML.)

<div class="container demo-1">
	<div class="main">
		<!-- Elastislide Carousel -->
		<ul id="carousel" class="elastislide-list">
			<li><a href="#"><img src="images/small/1.jpg" alt="image01" /></a></li>
			<li><a href="#"><img src="images/small/2.jpg" alt="image02" /></a></li>
			<li><a href="#"><img src="images/small/3.jpg" alt="image03" /></a></li>
			<li><a href="#"><img src="images/small/4.jpg" alt="image04" /></a></li>
			<li><a href="#"><img src="images/small/5.jpg" alt="image05" /></a></li>
			<li><a href="#"><img src="images/small/6.jpg" alt="image06" /></a></li>
			<li><a href="#"><img src="images/small/7.jpg" alt="image07" /></a></li>
			<li><a href="#"><img src="images/small/8.jpg" alt="image08" /></a></li>
			<li><a href="#"><img src="images/small/9.jpg" alt="image09" /></a></li>
			<li><a href="#"><img src="images/small/10.jpg" alt="image10" /></a></li>
			<li><a href="#"><img src="images/small/11.jpg" alt="image11" /></a></li>
			<li><a href="#"><img src="images/small/12.jpg" alt="image12" /></a></li>
			<li><a href="#"><img src="images/small/13.jpg" alt="image13" /></a></li>
			<li><a href="#"><img src="images/small/14.jpg" alt="image14" /></a></li>
			<li><a href="#"><img src="images/small/15.jpg" alt="image15" /></a></li>
			<li><a href="#"><img src="images/small/16.jpg" alt="image16" /></a></li>
			<li><a href="#"><img src="images/small/17.jpg" alt="image17" /></a></li>
			<li><a href="#"><img src="images/small/18.jpg" alt="image18" /></a></li>
			<li><a href="#"><img src="images/small/19.jpg" alt="image19" /></a></li>
			<li><a href="#"><img src="images/small/20.jpg" alt="image20" /></a></li>
		</ul>
		<!-- End Elastislide Carousel -->
	</div>
</div>

This structure is most important, because the classes added to the HTML controls are used inside the CSS and JavaScript files.
So, we just need to replace the “list items (li)” inside the “Unordered Lists” with Repeater Items, which eventually would look like the same structure and render all the image URLs inside List Items.

Step-3 : Create a Web Application and Add one aspx Page

After adding the aspx page to the Project, now we need to copy the js, css files and images from the “Downloaded Plugin” folders. So, Solution Explorer would look like…

Solution Explorer View

Solution Explorer View


NOTE : We have maintained the exact folder structure as in the Downloaded Plugin. Only “small” folder inside “images” folder is copied with another the “nav.png” image used for “previous next” buttons.

Step-4 : Let’s Design the aspx Page

Basically, we will copy the HTML present in index.html page and update it by adding one Repeater.
Now, the div would look like…

<div class="container demo-1">
	<div class="main">
		<ul id="carousel" class="elastislide-list">
			<asp:Repeater ID="mylist" runat="server">
				<ItemTemplate>
					<li><a href="#">
						<asp:Image ID="Image1" runat="server" ImageUrl='<%# "images/small/" + Eval("image")%>' />
					</a></li>
				</ItemTemplate>
			</asp:Repeater>
		</ul>
	</div>
</div>

:: Here ImageUrl Property is a combination of folders path and image name. Image Name is dynamically bound from the Datasource (explained in the next step), EVAL is used for this purpose only.
Next we will add the JavaScript and CSS files in the Page just like it appears in the index.html Page.
Now, most important thing is to add the following script inside the body.

<script type="text/javascript">
    $('#carousel').elastislide();
</script>

This code actually invokes the Slider to work. carousel is the id of the ul (Unordered list) element in HTML. This elastislide(); method is present in the Plugin js.

Step-5 : Bind the Repeater from Code Behind

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{
		BindRepeater();
	}
}

/// <summary>
/// This method binds the Image Slider.
/// </summary>
private void BindRepeater()
{
	DataTable dt = new DataTable();
	dt.Columns.Add("image");

	for (int i = 1; i <= 20; i++)
	{
		dt.Rows.Add(i + ".jpg");
	}

	mylist.DataSource = dt;
	mylist.DataBind();
}

This code is very simple. It binds the Repeater from a DataTable, which contains rows as image names. Image names are 1.jpg, 2.jpg till 19.jpg. You can put your image binding logic here to bind the Repeater.

Feedback Equips Me !!!

Please put your thoughts on the Project by commenting below the Blog. Like and Share, if you liked it.