Click here to Skip to main content
15,891,607 members
Articles / Web Development / ASP.NET

Database CRUD Operations In Business Sites With WCF REST, Web Services As Provider And JQuery, Javascript As Consumer : Zero Postback

Rate me:
Please Sign up or sign in to vote.
2.25/5 (3 votes)
23 Sep 2011CPOL4 min read 34K   1.3K   13  
This article explains how to perform CRUD operations in a web application with WCF REST services and ASMX services as provider and jQuery or javascript as consumer, eliminating postbacks totally
<%@ Page Title="" Language="C#" MasterPageFile="~/KovairSiteMasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Kovair.StudentPortal._Default" EnableViewState="false"
    EnableViewStateMac="false" EnableEventValidation="false" ValidateRequest="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>


<asp:Content ID="Content2" ContentPlaceHolderID="WebContentPlaceHolder" Runat="Server">

<script type = "text/javascript">
    $(function() {
        $('#ModDiv').hide();
        $('#<%=btnModify.ClientID%>').hide();
        $('#<%=btnDelete.ClientID%>').hide();
    });
    function GetStudentDetail() {
        $('#<%=btnModify.ClientID%>').hide();
        $('#<%=btnDelete.ClientID%>').hide();
        var control = $get('<%= this.ddlStudents.ClientID %>');
        var NewStudent = {};
        NewStudent.RollNo = 22;
        NewStudent.Name = "Jacob";
        // Create a data transfer object (DTO) with the proper structure.
        var DTO = { 'stu': NewStudent };
        var rollNo = control.options[control.selectedIndex].value;
        var name = control.options[control.selectedIndex].text;
        NewStudent.RollNo = rollNo;
        NewStudent.Name = name;
        $.ajax({
                type: 'POST',
                url: 'http://localhost/StudentService/StudentWebService.asmx/GetStudentDetail',
                data: JSON.stringify(DTO),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(response, status) {
                var list = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                var oup = "RollNo: " + list.RollNo.toString() + "  Marks: "  + list.Mark.toString();
                $('#<%=lblResult.ClientID %>').html(oup);
                },
                failure: function(response) {
                alert(response.d);
                }
               }
             );
        $('#<%=btnModify.ClientID%>').toggle(500);
        $('#<%=btnDelete.ClientID%>').toggle(500);
        return false;
    }
    function GetStudents() {
    $('#<%=ddlStudents.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
    $.ajax({
        type: 'GET',
        url: 'http://localhost/StudentService/StudentService.svc/GetStudents',
        data: {},
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(response, status) {
            var list = response;
            var control = $get('<%=ddlStudents.ClientID %>');
            control.options.length = 0;
            var newOption = new Option("Please Select ", "-1");
            control.options[0] = newOption;
            var i = 1;
            for (i = 1; i <= list.GetStudentsResult.length; i++) {
                newOption = new Option(list.GetStudentsResult[i - 1].Text, list.GetStudentsResult[i - 1].Value);
                control.options[i] = newOption;
            }
        },
        failure: function(response) {
            alert(response.d);
        }
    }
   );
   return false;
  }
  function ShowMod(isNew) {
      $('#ModDiv').toggle(500);
      if (isNew) {
          $get('<%= this.txtName.ClientID %>').focus();
      }
      else {
          
          var control = $get('<%= this.ddlStudents.ClientID %>');
          var name = control.options[control.selectedIndex].text;
          var marks = $get('<%= this.lblResult.ClientID %>').outerText;
          var gotMarks = marks.substring(marks.lastIndexOf(':') + 1);
          $get('<%= this.txtName.ClientID %>').value = name;
          $get('<%= this.txtMarks.ClientID %>').value = gotMarks;
          $get('<%= this.txtName.ClientID %>').focus();
      }
      return false;
  }
  function InsertMarks(roll) {
      var NewMarks = {};
      NewMarks.RollNo = roll;
      NewMarks.Mark = $get('<%= this.txtMarks.ClientID %>').value;
      var DTO2 = { 'stuMark': NewMarks };
      $.ajax({
          type: 'POST',
          url: 'http://localhost/StudentService/StudentService.svc/InsertMark',
          data: JSON.stringify(DTO2),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: function(response) {
              setTimeout("GetStudents()", 100);
          },
          failure: function(response) {
              alert(response.d);
          }
         }
        );
      $get('<%= this.txtName.ClientID %>').value = "";
      $get('<%= this.txtMarks.ClientID %>').value = "";
  }
  function SaveData(isNew) {
      var txtControl = $get('<%= this.txtName.ClientID %>');
      var rollNo = -99;
      var NewStudent = {};
      NewStudent.RollNo = rollNo;
      NewStudent.Name = txtControl.value;
      var DTO1 = { 'stuRec': NewStudent };
      if (isNew) {
          $.ajax({
              type: 'POST',
              url: 'http://localhost/StudentService/StudentService.svc/InsertStudent',
              data: JSON.stringify(DTO1),
              contentType: 'application/json; charset=utf-8',
              dataType: 'json',
              success: function(response) {
                  rollNo = response.InsertStudentResult;
                  setTimeout(function() { InsertMarks(rollNo) }, 100); 
              },
              failure: function(response) {
                  alert(response.d);
              }
          }
        );
      }
      else {
          var control = $get('<%= this.ddlStudents.ClientID %>');
          rollNo = control.options[control.selectedIndex].value;
          NewStudent.RollNo = rollNo;
          // Create a data transfer object (DTO) with the proper structure.
          DTO = { 'stuRec': NewStudent };
          $.ajax({
              type: 'POST',
              url: 'http://localhost/StudentService/StudentService.svc/UpdateStudent',
              data: JSON.stringify(DTO),
              contentType: 'application/json; charset=utf-8',
              dataType: 'json',
              success: function(response) { UpdateMarks(); },
              failure: function(response) {
                  alert(response.d);
              }
          }
        );
        $('#<%=btnModify.ClientID%>').toggle(500);
      }
      $('#ModDiv').toggle(500);
      $('#<%=lblResult.ClientID %>').html("");
      return false;
  }
  function UpdateMarks() {
      var control = $get('<%= this.ddlStudents.ClientID %>');
      rollNo = control.options[control.selectedIndex].value;
      var NewMark = {};
      NewMark.RollNo = rollNo;
      NewMark.Mark = $get('<%= this.txtMarks.ClientID %>').value;
      var DTO4 = { 'stuMark': NewMark };
      $.ajax({
          type: 'POST',
          url: 'http://localhost/StudentService/StudentService.svc/UpdateMarks',
          data: JSON.stringify(DTO4),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: function(response) { setTimeout("GetStudents()", 100); },
          failure: function(response) {
              alert(response.d);
          }
        }
      );
  }
  function DeleteStudent() {
      var rollNo = $get('<%= this.lblResult.ClientID %>').outerText;
      var gotRoll = rollNo.substring(rollNo.indexOf(':') + 1, rollNo.indexOf('M') - 1);
      var roll = parseInt(gotRoll.trim());
      var NewStudents = {};
      NewStudents.RollNo = roll;
      NewStudents.Name = "Jacob";
      // Create a data transfer object (DTO) with the proper structure.
      var DTO3 = { 'stuRec': NewStudents };
      $.ajax({
          type: 'POST',
          url: 'http://localhost/StudentService/StudentService.svc/DeleteStudent',
          data: JSON.stringify(DTO3),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: function(response) {
              setTimeout("GetStudents()", 100);
          },
          failure: function(response) {
              alert(response.d);
          }
      }
       );
      $('#<%=btnModify.ClientID%>').toggle(500);
      $('#<%=btnDelete.ClientID%>').toggle(500);
      $('#<%=lblResult.ClientID %>').html("");
      $('#<%=ddlStudents.ClientID %>').val("-1");
      return false;
  }
</script>
<div id="StudentDisplay">
    <span style="width:250px">
        <asp:DropDownList ID="ddlStudents" runat="server" onchange="javascript:return GetStudentDetail();" Height="30px" Width="200px">
        </asp:DropDownList>
    </span>
    <span style="width:150px">
        <asp:Label ID="lblResult" runat="server" Text="" Height="50px" Width="100px">
        </asp:Label>
    </span>
    <span style="width:100px">
        <asp:Button ID="btnModify" runat="server" Width="100px" Text="Modify" OnClientClick="javascript:return ShowMod(false);">
        </asp:Button>
    </span>
    <span style="width:100px">
        <asp:Button ID="btnInsert" runat="server" Width="100px" Text="Add New" OnClientClick="javascript:return ShowMod(true);">
        </asp:Button>
    </span>
    <span style="width:100px">
        <asp:Button ID="btnDelete" runat="server" Width="100px" Text="Delete" OnClientClick="javascript:return DeleteStudent();">
        </asp:Button>
    </span>
</div>
<div id = "ModDiv">
    <asp:Label ID="lblName" runat="server" Text="Name :" />
    <asp:TextBox ID="txtName" runat="server" />
    <asp:Label ID="lblMarks" runat="server" Text="Marks :" />
    <asp:TextBox ID= "txtMarks" runat="server" />
    <asp:Button ID="btnSave" runat="server" Width="50px" Text="Save" OnClientClick="javascript:return SaveData(false);" />
    <asp:Button ID="btnAdd" runat="server" Width="100px" Text="Add Record" OnClientClick="javascript:return SaveData(true);" />
</div>
</asp:Content>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Pramerica Systems Ireland
India India
CORE COMPETENCIES

 Design and Architecture for Microsoft SOA implementations using BizTalk, WCF, WF, SQL Server Integration Services & ESB Toolkit.

 Web Application design and implementation using ASP.NET MVC with jQuery & Entity Framework with LINQ for persistence layer.

 Designing and developing desktop applications using WPF, WinForms.

 SQL Server Database design & programming

EXPERIENCE SUMMARY

 Eleven years total, out of which 04 years as architect, 07 years as designer and developer in various Microsoft technologies like WinForms, ASP.NET WebForms, ASP.NET MVC, BizTalk, WCF, WF, WPF, SQL Server, LINQ, EF etc. Worked in various roles mainly architect, designer, team leader and developer.

 Hands on experience with ASP.NET web applications (both MVC and Web Forms) and desktop based applications as well as smart client applications using latest technologies harnessing .NET Framework 4.0, C# 4.0, ASP.NET 4.0, WCF, WF, WPF and LINQ.

 Hands-on working experience in Application integration, business process management and service oriented applications using BizTalk Server 2010, ESB Toolkit 2.1, WCF 4.0 services and SQL Server 2008 Integration Services.

 Thorough working knowledge of OOAD and agile / incremental development process.

 Experience in leading team of developers for on schedule project delivery with quality.

 Experience with low level programming like embedded C, C++ as well as systems programming on unix platform.
REMARKABLE PROFESSIONAL ACHIEVEMENTS

 Got Microsoft Community Contributor Award in year 2011 with MCC ID# 4034514.

 Published article in MSDN Magazine Feb 2011 edition on MDM with F#: http://msdn.microsoft.com/en-us/magazine/gg598923.aspx
http://www.codeproject.com/News/14767/Pattern-Matching-Database-Records-with-Fsharp.aspx

 Published highly popular article on BizTalk in www.dotnetcurry.com
http://www.dotnetcurry.com/ShowArticle.aspx?ID=683

 Umpteen blogs in BizTalk server forums and ESB toolkit forums.

Comments and Discussions