Editing ASP.NET ListView Control using JQuery AJAX and Web Services

http://www.ezzylearning.com/tutorial/editing-asp-net-listview-control-using-jquery-ajax-and-web-services
JQuery is growing in stature day by day and so as the number of interesting scenarios in which it can be used in modern web applications. One of the very common UI requirements is to display the tabular data on page in controls such as ASP.NET GridView or ListView and then provides record editing facility using a popup dialog through which user can update data in the backend database as well as in the front end control asynchronously without a full server post back. There are very few tutorials online, which shows how to put together a complete example of using ASP.NET ListView control to display data, JQuery code to display Popup Dialog, AJAX code to send asynchronous calls to the server, ADO.NET code to select/update backend database and ASP.NET web service. In this tutorial, I will show you how to use all these pieces of the jigsaw puzzle together to implement a complete online record editing scenario.
Before you start reading this tutorial I am making a silly assumption that you know the basics of ASP.NET ListView control and also know how to call web services using JQurey AJAX. If you don’t then I recommend that you must read my other tutorials on ListView control, JQuery, AJAX and Web services before reading this tutorial. Even if you are not fully familiar with all these technologies than don’t stop reading, just follow this tutorial from the start to end, and you will be able to understand everything quite easily without losing too many hairs on your head.
Editable Listview using JQuery

To get started, create an ASP.NET website and drag the ListView control on the page from the toolbox. ASP.NET ListView control is introduced in ASP.NET 3.5 and it enables you to bind and display data items individually or as a group. It supports paging, sorting, selections, editing, insertions, deletions and many other cool features. It also gives developers full control on the HTML markup rendered on the page with the help of templates. In this tutorial, we will use LayoutTemplate which defines the main layout of the control andItemTemplate which defines the data bound content to display for a single item. The following markup shows ListView control used in this tutorial. 

  
     
        
           
           
           
           
        
        
           
        

     
IDNameFee

  

  
     
        
            Edit                onclick="EditStudent(this);" />                    
        
        
            <%# Eval("ID") %>
        
        
            <%# Eval("Name")%>
        
        
            <%# Eval("Fee")%>
        
     
  

In the markup above, the ListView control LayoutTemplate is defining the main layout of the control using the HTML table element. The other noticeable thing is the use of onclick event for the img element which is callingEditStudent JavaScript function. The EditStudent function will display the following edit form in a popup dialog each time user will click the Edit Icon. Define the following editForm div element just below to the ListView control in your page HTML markup. 
editForm
" class="editForm">
  
     
        
        
Edit Student
            onclick="CloseEditStudentDialog();"
 style="cursor: pointer;">Close
        
     
     
         ID:
        
     
     
         Name:
        
     
     
         Fee:
        
     
     
        
        
            
        
     
  


You may have noticed that two more JavaScript functions CloseEditStudentDialog and UpdateStudent are being used in the edit form HTML markup above. I will show you the JavaScript code of all these functions later in this tutorial. 

Next step is to create an ASP.NET web service that will be responsible to fetch student records from the database table and will also provide a method to update the record. Add an ASP.NET web service in your project with the name StudentWebService.asmx and define two methods GetStudents and UpdateStudentin the code behind file of the web service. Here is the complete code for the web service.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class StudentWebService : System.Web.Services.WebService {

    public StudentWebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public DataTable GetStudents()
    {
        string constr = @"Server=TestServer; Database=SampleDB; uid=waqas; pwd=123";
        string query = "SELECT ID, Name, Fee FROM Students";
        SqlDataAdapter da = new SqlDataAdapter(query, constr);
        DataTable table = new DataTable();
        da.Fill(table);
        return table;
    }


    [WebMethod]    
    public int UpdateStudent(int id, string name, decimal fee)
    {
        SqlConnection con = null;
        string constr = @"Server=TestServer; Database=SampleDB; uid=waqas; pwd=123";
        string query = "UPDATE Students SET Name = @Name, Fee = @Fee WHERE ID = @ID";

        con = new SqlConnection(constr);
        SqlCommand command = new SqlCommand(query, con);
        command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = name;
        command.Parameters.Add("@Fee", SqlDbType.Decimal).Value = fee;
        command.Parameters.Add("@ID", SqlDbType.Int).Value = id;

        int result = -1;
        try
        {
            con.Open();
            result = command.ExecuteNonQuery();
        }
        catch (Exception)
        { }
        finally
        {
            con.Close();
        }
        return result;
    }
    
}

In the above code, notice the use of ScriptService attribute on top of the class definition. This attribute is required to communicate with the web service from JavaScript. For brevity, I used hard coded connection strings in the methods above. You can store connection strings in web.config in your web application. You may also need to change connection string parameters such as serverdatabaseuser id or password according to your machine environment. I used a simple database table Student with three columns ID, Name and Fee in this tutorial. You can create this table in your SQL Server database for the implementation of this tutorial. The code is using basic ADO.NET SqlConnection, SqlCommand, SqlAdapter and DataTable objects to retrieve and update data in the database. We need to call GetStudents method on the page load event to display student records on ListView control. Following code shows how to use the web service in Page Load event.
protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      StudentWebService service = new StudentWebService();
      ListView1.DataSource = service.GetStudents();
      ListView1.DataBind(); 
   }
}

Add the following CSS styles in the head section of your page and run the application. You will see the ListView control showing student records as shown in the figure below.


Editable Listview using JQuery

Now is the time to make small edit icon working and showing user the popup dialog form to edit student records. For this we need to write some JavaScript functions and JQuery code in the page. Add the following JQuery library reference in the head section of the page. 

Next add the HTML script block and declare some variables to keep track of the editable row and to store the current student data as shown below:


Inside ListView control, the edit icon image has defined onclick event, which calls EditStudent JavaScript function. So this is the first function you need to define in JavaScript code block. 
function EditStudent(editButton) 
{
   row = $(editButton).parent().parent();
   id = $("#id", row).text();
   name = $("#name", row).text();
   fee = $("#fee", row).text();
   row.addClass("highlightRow");
   DisplayEditStudentDialog();
   return false;
}

The EditStudent function is storing the reference of the current row in the row variable declared above. Then it finds the idname and fee span elements in the current row and stores their text in other three variables. Finally, it calls DisplayEditStudentDialog function to show the popup dialog.

function DisplayEditStudentDialog() 
{
   $("#spnID").text(id);
   $("#txtName").val(name);
   $("#txtFee").val(fee);
   $("#editForm").show();
}

The DisplayEditStudentDialog first stores the values of idname and fee variables in span and text boxes in the dialog box and then calls JQuery show method to display the following editForm on the screen.

Editable Listview using JQuery

When user clicks update button, the following UpdateStudent function is called that used JQuery AJAX function to call UpdateStudent method defined in Web Service code. It passes idname and fee as parameters in JSON format to the web service and on the success execution of the web service method it updates span elements in the ListView control and calls CloseEditStudentDialog. If you are not familiar with JQuery AJAX, JSON and Web Service calls and want to learn more about them then I will recommend you to read my other JQuery tutorials on this website. 
function UpdateStudent(e) 
{
   name = $("#txtName").val();
   fee = $("#txtFee").val();

   $.ajax({
      type: "POST",
      url: "StudentWebService.asmx/UpdateStudent",
      data: "{'id':'" + id + "', 'name':'" + name + "', 'fee':'" + fee + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(response) 
      {
         var result = response.d;
         if (result > 0) 
         {
            $("#name", row).text(name);
            $("#fee", row).text(fee);
            row.removeClass("highlightRow");
            CloseEditStudentDialog();
         }
         else 
         {
            alert('There is some error during update');
         }
      },
      failure: function(msg) 
      {
         alert(msg);
      }
   }); 
   return false;
}

Finally, we need CloseEditStudentDialog function to hide the popup dialog from the screen on successful update.
function CloseEditStudentDialog() 
{
   $("#editForm").hide();
   row.removeClass("highlightRow");
}

I hope you have learned many new techniques in this tutorial, and you have implemented the complete tutorial successfully. . 

Comments

Popular posts from this blog

SharePoint 2007 - Simple Task Dashboard

MERGE transformation in SSIS