What is the best way to update my server control following an INSERT operation using AJAX?

Is there a way to refresh my server control after an INSERT operation using AJAX?

This is my .aspx code:

<form id="form1" runat="server">
        <div>
            <asp:ListView ID="lv_familyrelation" runat="server" ItemPlaceholderID="RelationContainer" ItemType="DomainClasses.FAMILYRELATION">
                <LayoutTemplate>
                    <fieldset id="FieldSet1">

                        <legend>Relations</legend>
                        <br />
                        <a id="lbtnInitInsert" class="btn btn-primary btn-md white_cr" onclick="EditForInsert(this);"><span class="glyphicon glyphicon-plus-sign"></span></a>

                        <br />
                        <br />
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-lg-4">
                                    Code
                                </div>
                                <div class="col-lg-4">
                                    Insert
                                </div>
                                <div class="col-lg-4">
                                </div>

                            </div>
                        </div>
                        <asp:PlaceHolder ID="RelationContainer" runat="server"></asp:PlaceHolder>
                    </fieldset>
                </LayoutTemplate>
                <ItemTemplate>

                    <div class="container-fluid">

                        <div class="row">
                            <div class="col-lg-4 code">
                                <%#:Item.RELATION_CODE%>
                            </div>
                            <div class="col-lg-4 name">
                                <%#:Item.RELATION_NAME%>
                            </div>
                            <div class="col-lg-4">
                                <a id="lbtn_edit" class="btn btn-primary btn-md white_cr" onclick="Edit(this);"><span class="glyphicon glyphicon-pencil"></span></a>


                            </div>
                        </div>
                    </div>
                </ItemTemplate>
            </asp:ListView>
        </div>

        <div id="insertForm" class="container-fluid editForm">
            <div class="row">
                <div class="col-lg-6">
                    Add
                </div>
                <div class="col-lg-6">
                    <a onclick="CloseInsertDialog(); return false;" style="cursor: pointer;">Close</a>
                </div>


            </div>
            <div class="row">
                <div class="col-lg-6">
                    Code
                </div>
                <div class="col-lg-6">
                    Name
                </div>


            </div>
            <div class="row">

                <div class="col-lg-12 code_ins">
                    <asp:TextBox ID="txt_relation_code_ins" runat="server"></asp:TextBox>
                </div>
                <div class="col-lg-12 name_ins">
                    <asp:TextBox ID="txt_relation_name_ins" runat="server"></asp:TextBox>
                </div>

            </div>

            <div class="row">

                <div class="col-lg-12">
                    <input type="submit" id="btn_close" value="Close" onclick="CloseInsertDialog(); return false;" />

                    <input type="submit" id="btn_insert" value="Add" onclick="Insert(); return false;" />

                </div>

            </div>

        </div>

This is the script section :

<script type="text/javascript">

        var row;
        var id, name;

        function Edit(editButton) {


            row = $(editButton).parent().parent();
            id = $('.code', row).text().trim();
            name = $('.name', row).text().trim();


            row.addClass("highlightRow");
            DisplayEditDialog();
            return false;
        }

        function DisplayEditDialog() {
            $("#lbl_relation_code").text(id);
            $("#txt_relation_name").val(name);
            $("#editForm").show();
        }

        function EditForInsert(editButton) {

            $("#insertForm").show();

            return false;
        }

        function Insert(e) {

            name = $("#txt_relation_name_ins").val();
            id = $("#txt_relation_code_ins").val();
            $.ajax({
                type: "POST",
                url: "FamilyRelationService.asmx/Insert",
                data: "{'id':'" + id + "', 'name':'" + name + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var result = response.d;
                    if (result > 0) {
                        CloseInsertDialog();
                    }
                    else {
                        alert('Error...');
                    }
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
            return false;
        }

        function CloseInsertDialog() {
            $("#insertForm").hide();
        }

    </script>

This is my web service method :

[WebMethod]
        public int Insert(int id, string name)
        {
            int result = -1;
            try
            {
                using (HRCTX ctx = new HRCTX())
                {
                    using (FamilyRelationRepository familyRelationRepo = new FamilyRelationRepository(ctx))
                    {
                        FAMILYRELATION family = new FAMILYRELATION
                        {
                            RELATION_CODE = id,
                            RELATION_NAME = name,
                            State = StateInterface.State.Added

                        };
                        familyRelationRepo.InsertOrUpdate(family);
                        result = ctx.Save();

                    }
                }
            }
            catch (Exception ee)
            {

                throw;
            }
            return result;
        }

Answer №1

Once data has been inserted using a Webmethod, the next step is to retrieve the newly inserted row from the database and construct a string as shown below:

aspx.cs

 [WebMethod]
    public static string GetNewlyInsertedRecord()
    {
        return NewlyInsertt();
    }

public static string NewlyInsertt()
{
    dt = GetNewRecord();
    foreach (DataRow r in dt.Rows)
    {
        sb.Append(
           @"<div class='row'> 
                    < div class='col-lg-4 code'>" +
               r["Code"] +
                @"</div> 
                    <div class='col-lg-4 name'>" +
                r["Name"] +
                @"</div> 
                    <div class='col-lg-4'>
                    <a onclick = 'Edit(this);' class='btn btn-primary btn-md white_cr' id='lbtn_edit'><span class='glyphicon glyphicon-pencil'></span></a> "
            );
    }
    return sb.ToString();
}

In the CloseInsertDialog method in the Aspx file, append the response like this:

 $("#toappend").append(response.d);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inject CSS into an iframe containing a JavaScript form by iterating over a collection of iframes

My task is to manipulate an iframe (chatbox) once it's loaded on a webpage. This chatbox consists of four iframes, each with a different id that changes with every page load. Since the iframe that needs manipulation is always the last one in the list, ...

Exploring content within a nested directory on AWS S3

I'm currently experimenting with an ajax request in order to retrieve all image files from a specific subfolder within my S3 bucket. Even though I have set the subfolder to public access using the dropdown menu (view image for reference), I keep enco ...

fetching data from a component modified by another component in Svelte

In this particular component, I am capturing user input and storing it in variables. I would like this value to be automatically updated in another component when the submit button is clicked. <script> import { onMount } from "svelte"; ...

Selecting the most popular post from a Facebook group

Here is the JSON file that I am currently using JSON.parse(); in Google Apps Script. Currently, I have found a temporary solution with this code by selecting posts that have more than 15 likes. However, my goal is to be able to select the post with the ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Retrieve the foreign key value associated with the primary key in a separate table that is connected to multiple tables

I have a database structured in SQL Server and I am looking to retrieve the output using asp.net, LINQ, and C#. The database consists of 2 tables that are linked to one table with a one-to-one relationship. My question is, how can I determine which primar ...

Tips for creating a bitmap within a managed control

Currently, I am faced with a task involving a fingerprint sensor in the context of C# .NET. The sensor displays the captured fingerprint by interacting with a control, as demonstrated below: this.Sensor.SetDisplay((int)this.PictureBoxFingerprint.Handle); ...

Mobile users experiencing issues with Whatsapp share link functionality

Utilizing aspx to set up the whatsApp click to chat feature for sharing a link. The aspx code is : <a href='<%#"https://wa.me/?text="+ Server.UrlEncode(Request.Url.AbsoluteUri)%>' class="fa fa-whatsapp social-share-link a-fb-whatsapp" t ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

What is the maximum character limit for jQuery?

Here's a code snippet I'm working with: $.get("url") .done(function(data){ alert("success"); alert(JSON.stringify(data)); }) .fail(function(data){ alert("fail"); alert(JSON. ...

Ajax Form Compatibility Issue with Internet Explorer Versions 8 and 9

I have developed a form that utilizes Ajax to ensure the page does not refresh upon submission. The functionality works perfectly in Chrome and Firefox, but I encountered an issue when testing it on Internet Explorer (specifically versions 8 and 9). When a ...

Determine the total by multiplying the value of a dropdown menu and a text input field using jQuery when the values are changed

I am new to jQuery and JavaScript. I have a textbox and a select box, and when I enter a value in the textbox and select a value from the select box, I want to display the multiplication of both values in another textbox. I have tried doing this with two t ...

Comparing the variance in double data types between Java and C#

double in Java represents a 64-bit IEEE 754 floating-point number, while in C# it represents a 64-bit double-precision number in the IEEE 754 format. Despite both languages following the same specification, there seems to be a difference in the following ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Implementing "interactive user" dependency injection in ASP MVC: a step-by-step guide

I've developed a comprehensive engine that heavily relies on abstractions based on user interactions. This setup works seamlessly with WPF/Xamarin applications, as I can easily implement these abstractions using windows/forms. However, I've been ...

retrieve data properties from an object

Suppose I have the following setup: var myObj = [ { name: 'A', number: 'b1', level: 0 }, { name: 'B', number: 'b2', level: 0 }, ]; I need to figure out how to retrieve all the names and format them like this: ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Executing a function on Navbar Button click in Phonegap

Currently, I am developing an application for educational purposes. The application consists of a header, content section, and a navigation bar with two buttons. The body="onLoad()" function performs perfectly when the app is launched. However, when I cl ...