Detect Changes to Spectrum Colorpicker

Introduction

In this blog, we will see how to manage the default value of color picker so that we can detect if color is changed.

Background

In my current project, requirement came to check if there are changes on the page on a button click and show a modal alerting the user that “There are changes, do you want to save?”. I found a script which can be triggered to check the changes on the page. It worked perfectly with all input, select and textarea controls.

But if I have a colorpicker on the page, then it always told me that you have changes, even if I did not change the color in the picker. Let me explain more. The colorpicker used is Spectrum.

Step by Step

Suppose, I have one input, select and textarea on my page. One button to check if we have any change on these controls meaning if we edited/changed the field values.

<input />

<select>
    <option value="1">1</option>
    <option value="2" selected="selected">2</option>
    <option value="3">3</option>
</select>

<textarea>Hello World</textarea>

<button onclick="CheckForChanges()">
    Check For Changes
</button>

Now let’s check the click event code.

function CheckForChanges() {
  if (GetHasChanges()) {
      alert("Yes we have changes!!!");
  } else {
      alert("No changes!!!");
  }
}

I am not posting the GetHasChanges function here, you can see in the jsfiddle Demo.
So, see the picture below which tells what is before you click the button and what happens after you edit some field and click the button. It perfectly checking that we have a change.

Before and After Changes Done

Before and After Changes Done

With Colorpicker

Let’s add a colorpicker now.

<input id="colorpicker" style="display:none;" value="#000" />
$(document).ready(function() {
  $('#colorpicker').spectrum({
    preferredFormat: "hex"
  });
});

Demo – Demo With a Colorpicker
As you see in the picture below, everything is perfect.

Detecting Changes with Colorpicker

Detecting Changes with Colorpicker

Implementing Input Field inside the Colorpicker

This can be done by setting the showInput property to true

$(document).ready(function() {
  $('#colorpicker').spectrum({
    showInput: true,
    preferredFormat: "hex"
  });
});

Spectrum Colorpicker With ShowInput True

Spectrum Colorpicker With ShowInput True

What we get by doing this? Just a new input field inside the colorpicker so that we can give color hex.

Let’s get back to what we were doing.
OOPS!!! With no change, it is now saying that “Yes we have changes!!!”. See the picture below.

Checking changes with ShowInput true in Spectrum Colorpicker

Checking changes with ShowInput true in Spectrum Colorpicker


Demo – Demo to check changes with ShowInput true in Spectrum Colorpicker
So, I have not picked any color, still its detecting changes. We will find out the problem in next paragraph.

Research

I started research from Developer tool and debugged the method which is checking the changes. What I found, was very interesting.

Debugging GetHasChanges Function in Developer Tool

Debugging GetHasChanges Function in Developer Tool


So, as you see, it is detecting the change for an input. I, then, found it inside the HTML.

<input class="sp-input" type="text" spellcheck="false">

This is the same input which is inside the colorpicker. The problem it detected a change because it does not have a default value in place and value given to it is the color we provided (#000).

Solution

Have you guessed the solution!!! It’s easy. We just need to provide the default value as the same color value. Thus, it will only detect the change when an actual change is made. The final code looks like below. Highlighted the codes used to assign the default value.

$(document).ready(function() {
  $('#colorpicker').spectrum({
    showInput: true,
    preferredFormat: "hex"
  });

  $('.sp-container .sp-input').each(function() {
    this.defaultValue = this.value;
  });
});

Demo – Final Demo Detecting Colorpicker Change

Feedback

I would definitely appreciate, if you give feedback to my blog. If you find it interesting and useful, then please share with your friends and colleagues.

Thanks for reading, have a nice day!!!

Get Required Property from Complex json string in C# with Newtonsoft

Introduction

In this blog, I will tell you the trick to convert JSON string property to C# Object using Newtonsoft.

Illustration

Suppose the JSON string is like…

{
  "Success": true,
  "ComplexObject": {
    "NormalProp": "Test",
    "ListOfAnotherClass": [{
      "JustAStringProp": "We"
    }, {
      "JustAStringProp": "Got"
    }, {
      "JustAStringProp": "Values"
    }]
  }
}

Now, if I get this string from some method and try to process, I would need to convert this to C# objects. The structure would look something like below. To easily get the class structure, you can use any online tool like json2csharp.

class Result
{
	public bool Success { get; set; }
	public ComplextJsonClass ComplexObject { get; set; }
}

class ComplextJsonClass
{
	public string NormalProp { get; set; }
	public List<AnotherClass> ListOfAnotherClass { get; set; }
}

class AnotherClass
{
	public string JustAStringProp { get; set; }
}

What We Need?

So, for processing, I would like to get the “ComplexObject” property of this JSON string converted as “ComplextJsonClass” C# object. As the JSON string is complex with other property like “Success“, we only need the property “ComplexObject“, yet converted to a C# object.

How To Do That?

We will use Newtonsoft. You can easily find that from Nuget and add that as a reference to your project.

Solution

First of all, I will tell you how to generate this type of JSON.

var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

This “jsonString” comes as I mentioned in the beginning of the post. Now, we need to convert this JSON to a C# Object. For this, we need to use JsonConvert.DeserializeObject Method (String).

var jsonObject = JsonConvert.DeserializeObject(jsonString);

But, unfortunately, this alone won’t help us more to access the properties. We have to convert to a JObject, by which we can easily access the properties from the JSON.

var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);

After this, it is just a matter of getting the property by using jsonObject["ComplexObject"].

var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());
Convert to C# Object from Newtonsoft JObject

Convert to C# Object from Newtonsoft JObject

Full Code

var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

// Get the jsonString from complex object.
var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

//Now let's deserialize and convert to our required ComplextJsonClass object.
var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());

Feedback

Let me know if this trick helped you in any way in your projects or assignments. Re-post or share, if you liked it.

Thanks a lot for reading. Marry Christmas and Happy New Year.:)

EntityType: EntitySet ‘[Entity Name]’ is based on type ‘[Entity Name]’ that has no keys defined

So, the exception completely indicates us that it is not able to find a Key in model, which is defined in database for that entity.

Problem

When you design a model class for the entity, you define many properties including keys, if any. But how MVC would know that some property is a key and some other is a normal? There should be some rule, right? Yes, there is. And if you don’t follow that rule, you would definitely get the below exception.

EntityType: EntitySet '[Entity Name]' is based on type '[Entity Name]' that has no keys defined.

Solution

MVC will automatically recognize an entity’s Key if it follows the convention ‘Id’ or ‘EntityNameId’. Additionally, the entity must expose this as a PROPERTY AND it must be PUBLIC. If you don’t follow the convention, then you need to explicitly indicate that particular property as a Key by using an annotation. Let’s explore more below.

Example

Convention ‘Id’ or ‘EntityNameId’

public int Id { get; set; }

OR

public int EntityNameId { get; set; }

Using [Key] Attribute

Just put [Key] on top of your property (which is presenting primary key). Something like this.

[Key]
public int AnyName { get; set; }

Hope this Helps !!!

If you landed on this page by searching the issue somewhere, then I would like you to comment here if you have more queries or doubts. Thanks for reading the blog. Share if you care.:)

Digital Citizenship Celebration in Odisha on Community Day 2015

Community Day 2015 Highlights

Community Day 2015 Highlights


MSDC Team with the School Children

MSDC Team with the School Children


What could be more enjoyable than teaching technology to the young generation?

Children are our greatest treasure. They are our future. – Nelson Mandela

On the occasion of “Community Day 2015 (Sep 19, 2015)”, “Digital Citizenship” program kick started in India. This program is initiated by “India Microsoft MVP Community” with the help of MVPs all over the country.

Why this?

We in the community, do realize that, our young guns are still very far from getting basic facilities to explore internet and computer science. We have seen many videos on vision 2020 and how the world surrounding us going to change, but are we going to even understand how this is going to happen. If our young minds are not getting chance to touch and feel the computer or gadgets, then how come we see something which would change our life.

Don’t even think, the children are not interested to learn. I will bet on this. We have already seen the passion, enthusiasm and eagerness to learn computer science and its applications among those youth, who are always ignored.

The Driving Force

I have started my techie career in Mindfire Solutions and in these four years, I have learned a lot how to give my best in office as well as to share my knowledge and give that back to the society. Every Mindfirean is encouraged to work for technical communities, which defines, Mindfire has a unique work culture and ethics.

Planning

So, Microsoft Dev Community (MSDC) Odisha took this initiative very seriously to educate and spread the awareness on computers and technology to the citizens of Odisha. This is why this community was started in December 2014.

MSDC Presents Community Day 2015

MSDC Presents Community Day 2015

A group of MSDCians including me planned to visit two schools in one day that is 19th Sept 2015. The schools are situated in my district, “Nayagarh“. One is “NAC High School” and the other one is “Sri Aurobindo Integral High School”.

Visit to Schools prior to the Event Day

Before few days of the event, I visited the schools and interacted with children from different classes (7th to 10th) to check their interest on the event. I was overwhelmed with joy, when I found that they are so delighted to see someone who talks to them on computers or gadgets or robots. They asked me many question. Even I hijacked one class that day, after they pulled me to the classroom again to tell them something on computers and how it operates.

I was moved by the fact that my parents have made me so able, for which today I am standing tall and explaining computers to small kids, where I studied for five years. My teachers gave me immense support to conduct this workshop on 19th.

The Event Day

Alright, now everything is setup, children are ready, teachers are ready, so are the MSDC guys.

First School – NAC High School Nayagarh

The day has finally come. We (ten guys) traveled from Bhubaneswar to Nayagarh, which is almost 2 hours journey. After reaching, we could not believe our eyes, when we saw attendance of 100 instead of expected count of 50 in NAC High School. My friends from Nayagarh really worked hard to set up everything from arranging tables, chairs to setting up the projectors and electricity in that conference hall.

Importance of Education

We are all set now. Before some tech talks, Suvendu Giri (Co-Founder MSDC Odisha and Software Engineer, ESSPL) motivated the gathering by some inspirational videos thereby illustrated the importance of education and computer. I helped him a bit here.

Suvendu Giri and Tadit Dash | Importance of Education

Suvendu Giri and Tadit Dash | Importance of Education

Computer Basics

Okay, let’s talk some technology. Of course, we have to start from basics that is “Computer Funda !!! How Computer Works?”. Mr. Durga Charan Ojha, who is a System Administrator in Mindfire started teaching this and got many questions in return. He was able to answer every question. One interesting question was “Why this computer took birth?” Now ask this to yourself, if you want to answer, please feel free to comment below this post !!!

Durga Ojha and Prayash Mohapatra | Computer Fundamentals

Durga Ojha and Prayash Mohapatra | Computer Fundamentals

Durga showed mother boards to the students and Prayash Mohapatra (3rd year, B.Tech, CET) also helped him in showing a micro computer and explained to them about its usage.

Internet

Sohel Wahid (B.Tech, KIIT) then started his session giving a brief idea on the internet and how it is so powerful in today’s world. Students explored the power of internet and how that can be helpful in their studies.

Virus

The next session was on Virus, which was delivered by Ariz Eqbal (B.Tech, KIIT), to which, every student find interesting, learned a few basic things about Virus and clarified doubts.

Robotics

Last, but not the least, the most interesting topic “Robotics” was presented by Rajesh Kumar Sahoo (B.Tech, KIIT). He was not only able to grab the attention of the children, but also amazed by the fact that most of them were really wanted to build robots after learning from him.

Left - Sohel Wahid | Internet, Right Top - Ariz Eqbal | Virus, Right Down Rajesh Sahoo | Robotics

Left – Sohel Wahid | Internet, Right Top – Ariz Eqbal | Virus, Right Down Rajesh Sahoo | Robotics

Goodies

Now this is the prize distribution time. We have listed few students who answered the questions we asked in between sessions. Professor Dr. Gobinda Chandra Dash (Nayagarh Autonomous College) and Mr. Pradip Kumar Dakua (Teacher Geography, NAC High School) were the dignitaries who distributed the prizes and congratulated them for their passion.

Prize Distribution | NAC High School

Prize Distribution | NAC High School

We are finally hungry…

Afternoon time and the whole team is hungry!!! We headed to a restaurant nearby to have some lunch.

Lunch

Lunch

Second School – Sri Aurobindo Integral High School, Nayagarh

Then we continued our journey of knowledge to the second school “Sri Aurobindo Integral High School”.

These guys are more excited than we imagined. Suvendu and me again started with our motivation talks and give them a hint about what is going to happen, next.

Prayash Mohapatra (B.Tech, CET) sat in between the students and started playing a game. Before the students could make something in their mind, Prayash very cleverly introduced them to the world of computer programming. And, that through a game, really!!! Yes, you heard that right.

Prayash Mohapatra | Game with Programming

Prayash Mohapatra | Game with Programming


Rajesh again operated a small robot in front of them. He showed how our lifestyle would be in a smart house after few years through a video. That was really interesting.
Rajesh Robotics in Sri Aurobindo School

Rajesh | Robotics in Sri Aurobindo School

Goodies

Goodies distributed to the students who answered questions during sessions.

Prize Distribution | Sri Aurobindo Integral High School

Prize Distribution | Sri Aurobindo Integral High School

Effect

  • More schools taking interest to conduct this kind of event.
  • Students are asking to organize at least once in every month in their school.
  • We are continuously getting calls from students who ask doubt in computers.
  • Sasaka Prasasaka on Monday, 28th September, published one news on our event.
Community Day 2015 News on Sasaka Prasasaka 28th September

Community Day 2015 News on Sasaka Prasasaka 28th September

Roadmap

We are already planning to take this to as many schools as we can in Odisha. Not only schools, but we will also educate the citizens of every edge at least how to operate a smart phone.

Time to Think!!!

The response really inspired us and opened our eyes. We should not just sit for 8-10 hours in office and work and come back home with a good salary, rather we should share our knowledge in society which once fed and educated us. Don’t be selfish after getting all the help from your surrounding. If you work for you and your family, then what you are giving back to your mother land. Serving to the people, is serving the God, I believe.

Isn’t this a matter to think!!!

If every one of us is determined to go to their own school at least and teach them something you have learned over the years, then illiteracy will only be a word in dictionary. Possible, right!!! If you want to contribute, please start. If you want to join us, please feel free to contact us and tell us how you can bring the change in Odisha.

Sharing is caring.

The best way to find yourself is to lose yourself in the service of others” ‪- Mahatma Gandhi‬

Vote of Thanks

I would, personally, like to thank everyone, who was a part of this event and contributed their time and knowledge towards the community.

  • My teachers, without whose guidance, this event was not possible. They gave us confidence, which boosted us up.
  • Microsoft and India Mentor supported us in planning and executing the event successfully.
  • Thanks to Mr. Biplab Paul (Audience Evangelism Manager, India Communities) and Mr. Gandharv Rawat (Community Support Lead, India Communities) for initiating this program in India.
  • It would be my mistake if I don’t congratulate the MSDC Team, who did all the hard work and executed, this program. Team members include all the speakers and Pravasini Sahoo, Rojalin Sahoo, Suraj Sahoo, Nirmal Hota, Atul Das, Alok Bhanja, Manash Pritam, Dillip Das, Rakesh Pradhan, Biswajit Nayak.
Team MSDC in Community Day 2015

Team MSDC in Community Day 2015

Vande Mataram

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.

How to Select All Text in a TextBox on focus?

Select all Text in Safari

Select all Text in Safari

Introduction

This is small tip, yet very useful when you want to select all text inside a TextBox.

Background

This was a requirement for which I researched a lot and tested on multiple browsers and devices. Let me share the problem and solution below.

Problem

When profile page is shown for a user, the password fields are also populated. The characters in a password field are masked (shown as asterisks or circles). So, typical user experience would be to select all text when you click or focus into these fields, as user can’t see the password, he/she will definitely change the whole password. Therefore, the problem is to select all the text inside the password fields.

Solution

We are going to use jQuery for this task. Solution is not so straight forward as it seems. So, the first thing comes into mind is to handle the focus event. Yes, of course, we will use that. So, the code would look like below…

$('#txtPassword').on('focus', function () {
    this.select();
});

But this is not a cross browser solution and will fail in Safari.

So, what is cross browser?

Very tricky actually. We need to specify how much text we need to select. We can specify that using the selectionStart and selectionEnd properties.

$('#txtPassword').on('focus', function () {
    this.selectionStart = 0;
    this.selectionEnd = this.value.length;
});

Now, one last thing. We need to prevent mouseup event, because that is fired automatically after focus, which deselects all the text.

$('#txtPassword').on('focus', function () {
    this.selectionStart = 0;
    this.selectionEnd = this.value.length;
});
$("#txtPassword").on('mouseup', function (e) {
    e.preventDefault();
});

Full Demo

[Demo] Select All Text in a TextBox on focus

If you have any queries, do visit my blog and drop me a Contact Tadit Dash request.

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 !!!:)