Saturday 1 March 2014

insert edit update delete using web service in asp .net C#

Hello Friends !!
Web services are Web-based applications accessed using the protocols of the web to be used by the web applications. It is basically a class consisting of method that could use by other applications. In simple word it is a part of web application that provides facility to communicate one system to another system through http (Hyper Text Transfer Protocol).

In this post I will explain insert ,edit ,update and delete operation through web service in asp.net c#.Now I have described how to insert,edit,update and delete operation with the help of web service and using with linq to sql.Complete step are given below.

1.Open Visual Studio
2.Create a new Project (ASP.NET Web Service) name it (WebServiceCrudOpe).
When open “ASP.NET Web Service”.By Default some code are prewritten in Service1.cs page as shown in below image.


Here I am using linq to sql for the CRUD Operation by web service.
For the crud operation ,first I create a table as shown in below figure.


Next step is to add a new item “LINQ to SQL Classes”.
See below figure after drag and drop table.


Now next step is create method for Insert,Edit,Update and Delete operation in Service1.asmx.cs page
Service1.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.Linq;
namespace WebServiceCrudOpe
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        //Method for Insertind data into database
        [WebMethod]
        public dsh_webserviceCRUD InserData(dsh_webserviceCRUD obj)
        {
            dsh_webserviceCRUD webobj = new dsh_webserviceCRUD();
            webobj.Name = obj.Name;
            webobj.Address = obj.Address;
            webobj.ContactNo = obj.ContactNo;
            db.dsh_webserviceCRUDs.InsertOnSubmit(webobj);
            db.SubmitChanges();
            return webobj;
        }
        //Method for Read/Get data from database
        [WebMethod]
        public List<dsh_webserviceCRUD> ReadData()
        {
            List<dsh_webserviceCRUD> listdata = new List<dsh_webserviceCRUD>();
            listdata = (from o in db.dsh_webserviceCRUDs
                        select o).ToList();
            return listdata;
        }
        //Method for Get Specif ID from database
        [WebMethod]
        public List<dsh_webserviceCRUD> ReadSpecific(int id)
        {
            List<dsh_webserviceCRUD> listspecific = new List<dsh_webserviceCRUD>();
            listspecific = db.dsh_webserviceCRUDs.Where(o => o.Id == id).ToList();
            return listspecific;
        }
        //Method for Updating data of database
        [WebMethod]
        public dsh_webserviceCRUD UpdateRec(dsh_webserviceCRUD obj)
        {
            dsh_webserviceCRUD updatedata = new dsh_webserviceCRUD();
            updatedata = db.dsh_webserviceCRUDs.Where(o => o.Id == obj.Id).FirstOrDefault();
            updatedata.Name = obj.Name;
            updatedata.Address = obj.Address;
            updatedata.ContactNo = obj.ContactNo;

            db.SubmitChanges();
            return updatedata;
        }
        //Method for Deleting data of database
        [WebMethod]
        public dsh_webserviceCRUD DeleteRec(int id)
        {
            dsh_webserviceCRUD DelRec = new dsh_webserviceCRUD();
            DelRec = db.dsh_webserviceCRUDs.Where(o => o.Id.Equals(id)).FirstOrDefault();
            db.dsh_webserviceCRUDs.DeleteOnSubmit(DelRec);
            db.SubmitChanges();
            return DelRec;
        }
    }
}
Here “[WebMethod]” is responsible to execute code on web.
Now Run the Web Service .


After run webservice you get URL (http://localhost:58126/Service1.asmx) that shown in above figure.
Copy the URL for the further use.

Now Move to Make a client side Project for the use of Web Service.
3 .Open Visual Studio
4. Create a new Project (ASP.NET Web Application) name it (WebserviceCRUD).
After that I have design  Default.aspx page with three textbox ,one button and one GridView for CRUD operation.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebserviceCRUD._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style3
        {
            height: 41px;
        }
        .style4
        {
            height: 41px;
        }
        .style5
        {
            width: 38px;
            height: 41px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="height: 223px; width: 889px">
        <br />
        <table class="style1">
            <tr>
                <td class="style5">
                    Name:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox1" runat="server" Height="20px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style5">
                    Address:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style5">
                    ContactNo:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3" colspan="2">
                 <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" Height="33px"
                        Width="76px" />
        <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
                </td>
            </tr>
        </table>
        <br />
        <br />
       
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
        DataKeyNames="Id" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address">
                <ItemTemplate>
                    <asp:Label ID="lbladdress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ContactNO">
                <ItemTemplate>
                    <asp:Label ID="lblcontactno" runat="server" Text='<%#Eval("ContactNo") %>'> </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:ImageButton ID="editbtn" runat="server" Height="40px" ImageUrl="~/img/edit-128.png"
                        Width="44px" CommandName="edit" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:ImageButton ID="deletebtn" runat="server" ImageUrl="img/delete-24.png" Height="42px"
                        Width="39px" CommandName="delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>
Next step to add web service reference in project. Right click on project and select “Add Web Reference” as shown in below figure.


After select “Add Web Reference” you will get a window . In “Add Web Reference”window ,paste  URL (Which I copy in above scenario) within URL Textbox.Then Click on Go button,and see all available Web Service Method will appear on pane below.
Note give the specific “Web reference name “.I am using “localhost1”.


After click on “Add Reference” button, you can see  solution explorer, you will find “localhost1” is added in solution as shown in below figure.


After open  Default.aspx.cs and write following code.
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebserviceCRUD.localhost1;
using System.Data.Linq;
namespace WebserviceCRUD
{
    public partial class _Default : System.Web.UI.Page
    {
        localhost1.Service1 svobj = new Service1();
        static int pk_id;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GrdBind();
            }
        }
        private void GrdBind()
        {
            List<dsh_webserviceCRUD> listdata1 = svobj.ReadData().ToList();
            GridView1.DataSource = listdata1;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Button1.Text == "Submit")
            {
                dsh_webserviceCRUD data = svobj.InserData(GetControlData());
                if (data != null)
                {
                    Label1.Text = data.Name + "Record" + " " + "Submited Succesfully";
                    Label1.Visible = true;
                    GrdBind();
                    ClearControl();
                }
            }
            else if (Button1.Text == "Update")
            {
                dsh_webserviceCRUD data1 = svobj.UpdateRec(GetControlData());
                Button1.Text = "Submit";
                GrdBind();
                ClearControl();
                Label1.Text = data1.Name + "" + "Record Updated Successfully";
                Label1.Visible = true;
            }
        }
        private void ClearControl()
        {
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
            TextBox3.Text = string.Empty;
        }
        private dsh_webserviceCRUD GetControlData()
        {
            dsh_webserviceCRUD cntrlobj = new dsh_webserviceCRUD();
            cntrlobj.Name = TextBox1.Text;
            cntrlobj.Address = TextBox2.Text;
            cntrlobj.ContactNo = TextBox3.Text;
            cntrlobj.Id = pk_id;
            return cntrlobj;
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
            pk_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
            if (e.CommandName == "edit")
            {
                List<dsh_webserviceCRUD> data = svobj.ReadSpecific(pk_id).ToList();
                TextBox1.Text = data.ToList()[0].Name;
                TextBox2.Text = data.ToList()[0].Address;
                TextBox3.Text = data.ToList()[0].ContactNo;
                Button1.Text = "Update";
                Label1.Visible = false;
            }
            else if (e.CommandName == "delete")
            {
                dsh_webserviceCRUD dlrec = svobj.DeleteRec(pk_id);
                Label1.Text = dlrec.Name + "  " + "Record Deleted Successfully";
                Label1.Visible = true;
                GrdBind();
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }
    }
}
Run the application and see the output as below.


2 comments:

Popular Posts

Recent Posts

Sample Text

Stats

Powered by Blogger.

Popular Posts

Popular Posts

Join US on Facebook