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

Bind DropDownList from DataTable using AJAX WebMethod

DropDownList Bound from Ajax WebMethod

DropDownList Bound from Ajax WebMethod


We will see one Example to bind one DropDownList using jQuery Ajax and C# WebMethod.

How?

Easy !!!

  • Add a WebMethod to Code Behind page
  • Call to that WebMethod from aspx Page
  • Bind the DropDownList when call succeeds

Let’s see the code

WebMethod

Here we are just creating a Dummy DataTable and converting it to XML.

/// <summary>
/// This WebMethod returns the XML for a DropDownList having value and text.
/// </summary>
/// <param name="tableName">string: Name of the Table having DropDownList items.</param>
/// <returns>string: XML containing all the items.</returns>
[System.Web.Services.WebMethod]
public static string GetDropDownItems(string tableName)
{
    // Create a dummy DataTable.
    DataTable dt = new DataTable(tableName);
    dt.Columns.Add("OptionValue");
    dt.Columns.Add("OptionText");
    dt.Rows.Add("0", "Item 0");
    dt.Rows.Add("1", "Item 1");
    dt.Rows.Add("2", "Item 2");
    dt.Rows.Add("3", "Item 3");
    dt.Rows.Add("4", "Item 4");

    // Convert the DataTable to XML.
    string result;
    using (StringWriter sw = new StringWriter())
    {
        dt.WriteXml(sw);
        result = sw.ToString();
    }

    return result;
}

JavaScript GetDropDownData function

The following function would do a jQuery Ajax call for the WebMethod and bind the Data to the DropDownList.

function GetDropDownData() {
	// Get the DropDownList.
	var ddlTestDropDownListXML = $('#ddlTestDropDownListXML');
	
	// Provide Some Table name to pass to the WebMethod as a paramter.
	var tableName = "someTableName";

	$.ajax({
		type: "POST",
		url: "BindDropDownList.aspx/GetDropDownItems",
		data: '{tableName: "' + tableName + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (response) {
			// Now find the Table from response and loop through each item (row).
			$(response.d).find(tableName).each(function () {
				// Get the OptionValue and OptionText Column values.
				var OptionValue = $(this).find('OptionValue').text();
				var OptionText = $(this).find('OptionText').text();
				
				// Create an Option for DropDownList.
				var option = $("<option>" + OptionText + "</option>");
				option.attr("value", OptionValue);

				ddlTestDropDownListXML.append(option);
			});
		},
		failure: function (response) {
			alert(response.d);
		}
	});
}

Important: We are passing one parameter tableName to the WebMethod, which will be the Dummy Table Name and after conversion to XML, it becomes parent of each Row. Refer the following Screenshot of returned XML Schema as seen inside Firebug Console.

XML returned from WebMethod

XML returned from WebMethod

We can see that someTableName is one one node containing the OptionText and OptionValue of a particular Item. These are actually Rows of the Dummy DataTable before conversion to XML.

Your Inputs !

Will be highly appreciated. Please feel free to comment. If you like the Blog, share this among your friends and colleagues.