عملیات CRUD با استفاده از Json, Ado.Net,Stored Procedure

شنبه 9 آبان 1394

در این مقاله می خواهیم در مورد عملیات CRUD (چهار عمل اصلی) در asp.net mvc صحبت کنیم ، در این مقاله ما از stored procedure و Json استفاده کردیم .

عملیات CRUD با استفاده از Json, Ado.Net,Stored Procedure

قدم اول درست کردن پایگاه داده و طراحی جدول است در زیر script های ساخت جدول و Stored Procedure های آن را قرار داده ایم.

اول از همه یک پایگاه داده به نام SampleDB می سازیم .

بعد از ساخت پایگاه داده جدول به صورت زیر را می سازیم:

CREATE TABLE [dbo].[tblCustomer](  
    [CustID] [bigint] NOT NULL,  
    [CustName] [nvarchar](50) NULL,  
    [CustEmail] [nvarchar](50) NOT NULL,  
    [CustAddress] [nvarchar](256) NULL,  
    [CustContact] [nvarchar](50) NULL,  
 CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED   
(  
    [CustID] ASC,  
    [CustEmail] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  
  
GO

Stored Procedure:

اول از همه برای برگرداندن اطلاعات از sp زیر استفاده می کنیم:

    ALTER PROCEDURE [dbo].[CREATE_CUSTOMER]  
        -- Add the parameters for the stored procedure here  
    (  
         @CustName NVarchar(50)  
        ,@CustEmail NVarchar(50)  
        ,@CustAddress NVarchar(256)  
        ,@CustContact  NVarchar(50)  
    )  
    AS  
    BEGIN  
        ---- SET NOCOUNT ON added to prevent extra result sets from  
        SET NOCOUNT ON;  
      
        ---- Try Catch--  
        BEGIN TRY  
            BEGIN TRANSACTION  
      
            DECLARE @CustID Bigint  
                SET @CustID = isnull(((SELECT max(CustID) FROM [dbo].[tblCustomer])+1),'1')  
      
            -- Insert statements for procedure here  
            INSERT INTO [dbo].[tblCustomer] ([CustID],[CustName],[CustEmail],[CustAddress],[CustContact])  
            VALUES(@CustID,@CustName,@CustEmail,@CustAddress,@CustContact)  
            SELECT 1  
            COMMIT TRANSACTION  
        END TRY  
        BEGIN CATCH  
                DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;  
                SELECT @ErrorMessage = ERROR_MESSAGE(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE();  
                RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);  
            ROLLBACK TRANSACTION  
        END CATCH  
      
    END  

برای اضافه کردن رکورد جدید از sp زیر استفاده نمایید:

    ALTER PROCEDURE [dbo].[CREATE_CUSTOMER]  
        -- Add the parameters for the stored procedure here  
    (  
         @CustName NVarchar(50)  
        ,@CustEmail NVarchar(50)  
        ,@CustAddress NVarchar(256)  
        ,@CustContact  NVarchar(50)  
    )  
    AS  
    BEGIN  
        ---- SET NOCOUNT ON added to prevent extra result sets from  
        SET NOCOUNT ON;  
      
        ---- Try Catch--  
        BEGIN TRY  
            BEGIN TRANSACTION  
      
            DECLARE @CustID Bigint  
                SET @CustID = isnull(((SELECT max(CustID) FROM [dbo].[tblCustomer])+1),'1')  
      
            -- Insert statements for procedure here  
            INSERT INTO [dbo].[tblCustomer] ([CustID],[CustName],[CustEmail],[CustAddress],[CustContact])  
            VALUES(@CustID,@CustName,@CustEmail,@CustAddress,@CustContact)  
            SELECT 1  
            COMMIT TRANSACTION  
        END TRY  
        BEGIN CATCH  
                DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;  
                SELECT @ErrorMessage = ERROR_MESSAGE(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE();  
                RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);  
            ROLLBACK TRANSACTION  
        END CATCH  
      
    END  

برای ویرایش رکورد از sp زیر استفاده نمایید:

    ALTER PROCEDURE [dbo].[UPDATE_CUSTOMER]  
        -- Add the parameters for the stored procedure here  
         @CustID BIGINT  
        ,@CustName NVarchar(50)  
        ,@CustEmail NVarchar(50)  
        ,@CustAddress NVarchar(256)  
        ,@CustContact  NVarchar(50)  
    AS  
    BEGIN  
        ---- SET NOCOUNT ON added to prevent extra result sets from  
        SET NOCOUNT ON;  
      
        ---- Try Catch--  
        BEGIN TRY  
            BEGIN TRANSACTION  
      
            -- Update statements for procedure here  
            UPDATE [dbo].[tblCustomer]  
            SET [CustName] = @CustName,  
                [CustAddress] = @CustAddress,  
                [CustContact] = @CustContact  
            WHERE [CustID] = @CustID AND [CustEmail] = @CustEmail  
            SELECT 1  
            COMMIT TRANSACTION  
        END TRY  
        BEGIN CATCH  
                DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;  
                SELECT @ErrorMessage = ERROR_MESSAGE(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE();  
                RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);  
            ROLLBACK TRANSACTION  
        END CATCH  
      
    END  

برای حذف رکورد موردن نظر از sp زیر استفاده نمایید:

    ALTER PROCEDURE [dbo].[DELETE_CUSTOMER]  
        -- Add the parameters for the stored procedure here  
          @CustID BIGINT  
    AS  
    BEGIN  
        ---- SET NOCOUNT ON added to prevent extra result sets from  
        SET NOCOUNT ON;  
      
        ---- Try Catch--  
        BEGIN TRY  
            BEGIN TRANSACTION  
      
            -- Delete statements for procedure here  
            DELETE [dbo].[tblCustomer]  
            WHERE [CustID] = @CustID   
            SELECT 1  
            COMMIT TRANSACTION  
        END TRY  
        BEGIN CATCH  
                DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;  
                SELECT @ErrorMessage = ERROR_MESSAGE(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE();  
                RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);  
            ROLLBACK TRANSACTION  
        END CATCH  
      
    END  

برای نمایش جزئیات رکورد از sp زیر استفاده می کنید:

    ALTER PROCEDURE [dbo].[VIEW_CUSTOMER]  
        -- Add the parameters for the stored procedure here  
        @CustID BIGINT  
    AS  
    BEGIN  
        -- SET NOCOUNT ON added to prevent extra result sets from  
        SET NOCOUNT ON;  
        -- Select statements for procedure here  
      
        SELECT * FROM [dbo].[tblCustomer]  
        WHERE [CustID] = @CustID   
    END  

یک پروژه ی جدید به صورت زیر می سازید:

پنجره ی جدیدی باز می شود که باید MVC را انتخاب نمایید.

وقتی کلیک Ok را بزنید پنجره ای به صورت زیر باز خواهد شد:

گام بعدی ایجاد یک model جدید است، از سمت چپ راست کلیک کرده و گزینه ی Ado.Net  Entity DataModel را انتخاب می نمایید.

قدم بعدی جدول مورد نظر را انتخاب نمایید:

حالا به سمت Design UI می روید و ما از یک Partial View برای نمایش لیست استفاده می کنیم.

در قسمت Index.cshtml کد زیر را بنویسید:

    @{  
        ViewBag.Title = "Index";  
    }  
      
    <h2>Index</h2>  
    <p>  
        @Html.ActionLink("Create New", "Create")  
    </p>  
      
    <!-- list -->  
    <div id="resultCust"></div>  
    <div id="loader" style="text-align: center; display: none; margin-bottom: 20px;">  
        <img alt="Loading" src="@Url.Content("~/Content/loader.gif")" /> Loading...  
    </div>  
    <!-- list -->  
      
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script type="text/javascript">  
      
        var inProgress = false;  
        $(document).ready(function () {  
      
            //======================Default Load================//  
            inProgress = true;  
            $("#loader").show();  
            $.get("@Url.Action("GetCustomer", "Customer")", { "RowCountPerPage": 5 },  
                       function (data) {  
                           $("#resultCust").append(data);  
                           $("#loader").hide();  
                           inProgress = false;  
                       });  
      
            //======================UL SCroll Load================//  
            var page = 1;  
            var _inCallback = false;  
      
            $(window).scroll(function () {  
      
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {  
                    if (page > -1 && !_inCallback) {  
                        _inCallback = true;  
                        page++;  
                        $("#loader").show();  
                        $.get("@Url.Action("GetCustomer_Scroll", "Customer")", { "PageNo": page, "RowCountPerPage": 5 },  
                         function (data) {  
                             if (data != '') {  
                                 $("#resultCust").append(data);  
                             }  
                             else {  
                                 page = -1;  
                             }  
                             $("#loader").hide();  
                             _inCallback = false;  
                         });  
                    }  
                }  
            });  
        });  
      
    </script>  
    @model IEnumerable<CRUD_MVC5.Models.tblCustomer>  
      
      
    @foreach (var item in Model)  
    {  
        <div>  
            <strong>Name: @Html.DisplayFor(modelItem => item.CustName)</strong>  
        </div>  
        <div>  
            Adddress: @Html.DisplayFor(modelItem => item.CustAddress)  
        </div>  
        <div>  
            @Html.DisplayFor(modelItem => item.CustEmail)  
        </div>  
        <div>  
            @Html.DisplayFor(modelItem => item.CustContact)  
        </div>  
        <div>  
            @Html.ActionLink("Edit", "Edit", new { id = item.CustID }) |  
            @Html.ActionLink("Delete", "Delete", new { id = item.CustID }, new { @class = "delete", @id = item.CustID })  
        </div>  
        <hr />  
    }  
      
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script src="~/Scripts/jquery.validate.min.js"></script>  
      
    <script type="text/javascript">  
        $(document).ready(function () {  
      
            $('a.delete').click(function (e) {  
                e.preventDefault();  
      
                var CustomerId = e.target.id;  
                var flag = confirm('You are about to delete Customer ID ' + CustomerId + ' permanently.Are you sure you want to delete this record?');  
                if (flag) {  
                    $.ajax({  
                        url: '/Customer/Delete',  
                        async: false,  
                        type: "POST",  
                        data: { id: CustomerId },  
                        dataType: "json",  
                        success: function (data, textStatus, jqXHR) {  
                            if (data.Message == 1) {  
                                //alert('Record Deleted!');  
                                $("#" + CustomerId).parent().parent().remove();  
                                window.location.href = '/Customer';  
                            }  
                            else {  
                                alert('Record not Affected to DataBase!!');  
                            }  
      
                            $("#loader").hide();  
                        },  
                        error: function (jqXHR, textStatus, errorThrown) {  
                            alert(jqXHR + "-" + textStatus + "-" + errorThrown);  
                        }  
                    });  
                }  
                return false;  
            });  
        });  
    </script>      

در این View ما یک شی Json به متد Action میفرستیم، و آن Action متد ،نتیجه ی Resault را بر می گرداند.

    @model CRUD_MVC5.Models.tblCustomer  
      
    @{  
        ViewBag.Title = "Create";  
    }  
      
    <h2>Create</h2>  
      
    <div id="loader" style="text-align: center; display: none; margin-bottom: 20px;">  
        <img alt="Loading" src="@Url.Content("~/Content/loader.gif")" /> Loading...  
    </div>  
      
    @using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "CustomerForm", @class = "form" }))  
    {  
        @Html.AntiForgeryToken()  
      
        <div class="form-horizontal">  
            <h4>Create Customer</h4>  
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustName, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustName, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustName, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustEmail, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustEmail, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustAddress, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustAddress, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustAddress, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustContact, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustContact, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustContact, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="Create" class="btn btn-default" id="SubmitForm" />  
                </div>  
            </div>  
        </div>  
    }  
      
    <div>  
        @Html.ActionLink("Back to List", "Index")  
    </div>  
      
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script src="~/Scripts/jquery.validate.min.js"></script>  
      
    <script type="text/javascript">  
        $(document).ready(function () {  
      
            $("#SubmitForm").click(function (e) {  
                e.preventDefault();  
                $("#loader").show();  
      
                var model_data = {};  
                model_data.CustName = $("#CustName").val();  
                model_data.CustEmail = $("#CustEmail").val();  
                model_data.CustAddress = $("#CustAddress").val();  
                model_data.CustContact = $("#CustContact").val();  
      
                if (model_data.CustEmail != '') {  
      
                    $.ajax({  
                        url: '/Customer/Create',  
                        async: false,  
                        type: "POST",  
                        data: JSON.stringify(model_data),  
                        dataType: "json",  
                        contentType: "application/json; charset=utf-8",  
                        success: function (data, textStatus, jqXHR) {  
                            if (data.Message == 1) {  
                                alert('Record Successfully Saved!');  
                                window.location.href = '/Customer';  
                            }  
                            else {  
                                alert('Record not Affected to DataBase!!');  
                            }  
      
                            $("#loader").hide();  
                        },  
                        error: function (jqXHR, textStatus, errorThrown) {  
                            alert(jqXHR + "-" + textStatus + "-" + errorThrown);  
                        }  
                    });  
                }  
                else {  
                    return;  
                }  
            });  
        });  
    </script>  

حالا قسمت ویرایش :

    @model CRUD_MVC5.Models.tblCustomer  
      
    @{  
        ViewBag.Title = "Edit";  
    }  
      
    <h2>Edit</h2>  
      
    <div id="loader" style="text-align: center; display: none; margin-bottom: 20px;">  
        <img alt="Loading" src="@Url.Content("~/Content/loader.gif")" /> Loading...  
    </div>  
      
    @using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "CustomerForm", @class = "form" }))  
    {  
        @Html.AntiForgeryToken()  
          
        <div class="form-horizontal">  
            <h4>Edit Customer</h4>  
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            @Html.HiddenFor(model => model.CustID)  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustName, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustName, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustName, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            @Html.HiddenFor(model => model.CustEmail)  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustAddress, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustAddress, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustAddress, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.CustContact, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.CustContact, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.CustContact, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="Create" class="btn btn-default" id="SubmitForm" />  
                </div>  
            </div>  
        </div>  
    }  
      
    <div>  
        @Html.ActionLink("Back to List", "Index")  
    </div>  
      
      
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script src="~/Scripts/jquery.validate.min.js"></script>  
    <script type="text/javascript">  
        $(document).ready(function () {  
      
            $("#SubmitForm").click(function (e) {  
                e.preventDefault();  
                $("#loader").show();  
      
                var model_data = {};  
                model_data.CustID = $("#CustID").val();  
                model_data.CustName = $("#CustName").val();  
                model_data.CustEmail = $("#CustEmail").val();  
                model_data.CustAddress = $("#CustAddress").val();  
                model_data.CustContact = $("#CustContact").val();  
      
                if (model_data.CustEmail != '') {  
      
                    $.ajax({  
                        url: '/Customer/Edit',  
                        async: false,  
                        type: "POST",  
                        data: JSON.stringify(model_data),  
                        dataType: "json",  
                        contentType: "application/json; charset=utf-8",  
                        success: function (data, textStatus, jqXHR) {  
                            if (data.Message == 1) {  
                                alert('Record Successfully Saved!');  
                                window.location.href = '/Customer';  
                            }  
                            else {  
                                alert('Record not Affected to DataBase!!');  
                            }  
      
                            $("#loader").hide();  
                        },  
                        error: function (jqXHR, textStatus, errorThrown) {  
                            alert(jqXHR + "-" + textStatus + "-" + errorThrown);  
                        }  
                    });  
                }  
                else {  
                    return;  
                }  
            });  
        });  
    </script>  

حالا قسمت نوشتن کدهای قسمت Controller است، کلیک راست کرده و یک Controller جدیدی را می سازید:

حالا نوبت ساخت یک کنترل برای انجام عملیات CRUD است:

    // Customer Controller   
    public class CustomerController : Controller  
    {  
        // GET: Customer  
        public ActionResult Index()  
        {  
            return View();  
        }  
      
        // GET: Customer  
        [HttpGet]  
        public ActionResult GetCustomer(int RowCountPerPage)  
        {  
            try  
            {  
                int PageNo = 0;  
                int IsPaging = 0;  
      
                CrudDataService objCrd = new CrudDataService();  
                List<tblCustomer> modelCust = objCrd.GetCustomerList(PageNo, RowCountPerPage, IsPaging);  
                return PartialView("_ListCustomer", modelCust);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
      
        // GET: Customer/InfinitScroll  
        [HttpGet]  
        public ActionResult GetCustomer_Scroll(int PageNo, int RowCountPerPage)  
        {  
            try  
            {  
                Thread.Sleep(2000);  
                int IsPaging = 1;  
                CrudDataService objCrd = new CrudDataService();  
                List<tblCustomer> modelCust = objCrd.GetCustomerList(PageNo, RowCountPerPage, IsPaging);  
                return PartialView("_ListCustomer", modelCust);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
      
        // GET: Customer/Create  
        public ActionResult Create()  
        {  
            return View();  
        }  
      
        // GET: Customer/Create  
        [HttpPost]  
        public JsonResult Create(tblCustomer objCust)  
        {  
            try  
            {  
                CrudDataService objCrd = new CrudDataService();  
                Int32 message = 0;  
      
                if ((objCust.CustName != null) && (objCust.CustEmail != null)) message = objCrd.InsertCustomer(objCust);  
                else message = -1;  
                return Json(new  
                {  
                    Success = true,  
                    Message = message  
                });  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
      
      
        // GET: Customer/Edit  
        public ActionResult Edit()  
        {  
            return View();  
        }  
      
        // GET: Customer/Edit  
        [HttpGet]  
        public ActionResult Edit(long? id)  
        {  
            try  
            {  
                CrudDataService objCrd = new CrudDataService();  
                tblCustomer modelCust = objCrd.GetCustomerDetails(id);  
                return View(modelCust);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
      
        // GET: Customer/Edit  
        [HttpPost]  
        public JsonResult Edit(tblCustomer objCust)  
        {  
            try  
            {  
                CrudDataService objCrd = new CrudDataService();  
                Int32 message = 0;  
                message = objCrd.UpdateCustomer(objCust);  
                return Json(new  
                {  
                    Success = true,  
                    Message = message  
                });  
      
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
      
      
        // GET: Customer/Delete  
        [HttpPost]  
        public JsonResult Delete(long? id)  
        {  
            try  
            {  
                CrudDataService objCrd = new CrudDataService();  
                Int32 message = 0;  
                message = objCrd.DeleteCustomer(id);  
                return Json(new  
                {  
                    Success = true,  
                    Message = message  
                });  
      
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
    }  

یک راه ساده تر استفاده از Ado.net و sp است که در web.config می توانید قطعه کد زیر را بنویسد:

<connectionStrings>  
   <add name="dbConn" connectionString="Data source=DESKTOP-4L9DM2J; Initial Catalog=SampleDB; User Id=sa; Password=sa@123" providerName="System.Data.SqlClient"/>  
</connectionStrings> 

حالا نیاز به تعریف یک کلاس است که این کلاس اتصال به بانک را تعریف می کند.

// Database Connection  
public class dbConnector  
{  
    private SqlConnection SqlConn = null;  
  
    public SqlConnection GetConnection  
    {  
        get { return SqlConn; }  
        set { SqlConn = value; }  
    }  
  
    public dbConnector()  
    {  
        string ConnectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;  
        SqlConn = new SqlConnection(ConnectionString);  
    }  
}  

برای انجام عملیات چهارگانه ما نیاز به کلاس CrudDataService ، در این کلاس ما پنج متد که با پایگاه داده در ارتباط است را صدا می زنیم به صورت زیر:

    // Database Service  
    public class CrudDataService  
    {  
        public List<tblCustomer> GetCustomerList(int PageNo, int RowCountPerPage, int IsPaging)  
        {  
            dbConnector objConn = new dbConnector();  
            SqlConnection Conn = objConn.GetConnection;  
            Conn.Open();  
      
            try  
            {  
                List<tblCustomer> _listCustomer = new List<tblCustomer>();  
                //_listCustomer = null;  
      
                if (Conn.State != System.Data.ConnectionState.Open)  
                    Conn.Open();  
      
                SqlCommand objCommand = new SqlCommand("READ_CUSTOMER", Conn);  
                objCommand.CommandType = CommandType.StoredProcedure;  
                objCommand.Parameters.AddWithValue("@PageNo", PageNo);  
                objCommand.Parameters.AddWithValue("@RowCountPerPage", RowCountPerPage);  
                objCommand.Parameters.AddWithValue("@IsPaging", IsPaging);  
                SqlDataReader _Reader = objCommand.ExecuteReader();  
      
                while (_Reader.Read())  
                {  
                    tblCustomer objCust = new tblCustomer();  
                    objCust.CustID = Convert.ToInt32(_Reader["CustID"]);  
                    objCust.CustName = _Reader["CustName"].ToString();  
                    objCust.CustEmail = _Reader["CustEmail"].ToString();  
                    objCust.CustAddress = _Reader["CustAddress"].ToString();  
                    objCust.CustContact = _Reader["CustContact"].ToString();  
                    _listCustomer.Add(objCust);  
      
                }  
      
                return _listCustomer;  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            finally  
            {  
                if (Conn != null)  
                {  
                    if (Conn.State == ConnectionState.Open)  
                    {  
                        Conn.Close();  
                        Conn.Dispose();  
                    }  
                }  
            }  
        }  
      
        public tblCustomer GetCustomerDetails(long? id)  
        {  
      
            dbConnector objConn = new dbConnector();  
            SqlConnection Conn = objConn.GetConnection;  
            Conn.Open();  
      
            try  
            {  
                tblCustomer objCust = new tblCustomer();  
      
                if (Conn.State != System.Data.ConnectionState.Open)  
                    Conn.Open();  
      
                SqlCommand objCommand = new SqlCommand("VIEW_CUSTOMER", Conn);  
                objCommand.CommandType = CommandType.StoredProcedure;  
                objCommand.Parameters.AddWithValue("@CustID", id);  
                SqlDataReader _Reader = objCommand.ExecuteReader();  
      
                while (_Reader.Read())  
                {  
                    objCust.CustID = Convert.ToInt32(_Reader["CustID"]);  
                    objCust.CustName = _Reader["CustName"].ToString();  
                    objCust.CustEmail = _Reader["CustEmail"].ToString();  
                    objCust.CustAddress = _Reader["CustAddress"].ToString();  
                    objCust.CustContact = _Reader["CustContact"].ToString();  
                }  
      
                return objCust;  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            finally  
            {  
                if (Conn != null)  
                {  
                    if (Conn.State == ConnectionState.Open)  
                    {  
                        Conn.Close();  
                        Conn.Dispose();  
                    }  
                }  
            }  
        }  
      
        public Int32 InsertCustomer(tblCustomer objCust)  
        {  
            dbConnector objConn = new dbConnector();  
            SqlConnection Conn = objConn.GetConnection;  
            Conn.Open();  
      
            int result = 0;  
      
            try  
            {  
                if (Conn.State != System.Data.ConnectionState.Open)  
                    Conn.Open();  
      
                SqlCommand objCommand = new SqlCommand("CREATE_CUSTOMER", Conn);  
                objCommand.CommandType = CommandType.StoredProcedure;  
                objCommand.Parameters.AddWithValue("@CustName", objCust.CustName);  
                objCommand.Parameters.AddWithValue("@CustEmail", objCust.CustEmail);  
                objCommand.Parameters.AddWithValue("@CustAddress", objCust.CustAddress);  
                objCommand.Parameters.AddWithValue("@CustContact", objCust.CustContact);  
      
                result = Convert.ToInt32(objCommand.ExecuteScalar());  
      
                if (result > 0)  
                {  
                    return result;  
                }  
                else  
                {  
                    return 0;  
                }  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            finally  
            {  
                if (Conn != null)  
                {  
                    if (Conn.State == ConnectionState.Open)  
                    {  
                        Conn.Close();  
                        Conn.Dispose();  
                    }  
                }  
            }  
        }  
      
        public Int32 UpdateCustomer(tblCustomer objCust)  
        {  
            dbConnector objConn = new dbConnector();  
            SqlConnection Conn = objConn.GetConnection;  
            Conn.Open();  
      
            int result = 0;  
      
            try  
            {  
                if (Conn.State != System.Data.ConnectionState.Open)  
                    Conn.Open();  
      
                SqlCommand objCommand = new SqlCommand("UPDATE_CUSTOMER", Conn);  
                objCommand.CommandType = CommandType.StoredProcedure;  
                objCommand.Parameters.AddWithValue("@CustID", objCust.CustID);  
                objCommand.Parameters.AddWithValue("@CustName", objCust.CustName);  
                objCommand.Parameters.AddWithValue("@CustEmail", objCust.CustEmail);  
                objCommand.Parameters.AddWithValue("@CustAddress", objCust.CustAddress);  
                objCommand.Parameters.AddWithValue("@CustContact", objCust.CustContact);  
      
                result = Convert.ToInt32(objCommand.ExecuteScalar());  
      
                if (result > 0)  
                {  
                    return result;  
                }  
                else  
                {  
                    return 0;  
                }  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            finally  
            {  
                if (Conn != null)  
                {  
                    if (Conn.State == ConnectionState.Open)  
                    {  
                        Conn.Close();  
                        Conn.Dispose();  
                    }  
                }  
            }  
        }  
      
        public Int32 DeleteCustomer(long? id)  
        {  
            dbConnector objConn = new dbConnector();  
            SqlConnection Conn = objConn.GetConnection;  
            Conn.Open();  
      
            int result = 0;  
      
            try  
            {  
                if (Conn.State != System.Data.ConnectionState.Open)  
                    Conn.Open();  
      
                SqlCommand objCommand = new SqlCommand("DELETE_CUSTOMER", Conn);  
                objCommand.CommandType = CommandType.StoredProcedure;  
                objCommand.Parameters.AddWithValue("@CustID", id);  
                result = Convert.ToInt32(objCommand.ExecuteScalar());  
      
                if (result > 0)  
                {  
                    return result;  
                }  
                else  
                {  
                    return 0;  
                }  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            finally  
            {  
                if (Conn != null)  
                {  
                    if (Conn.State == ConnectionState.Open)  
                    {  
                        Conn.Close();  
                        Conn.Dispose();  
                    }  
                }  
            }  
        }  
    }  

زمانی که برنامه را اجرا بگیرید به صورت زیر خواهد بود:

در این مقاله هدف استفاده از json برای قسمت بالای صفحه و بار گذاری اطلاعات است

فایل های ضمیمه

برنامه نویسان

نویسنده 3355 مقاله در برنامه نویسان

کاربرانی که از نویسنده این مقاله تشکر کرده اند

در صورتی که در رابطه با این مقاله سوالی دارید، در تاپیک های انجمن مطرح کنید