Refresh ListView after insert record to Database using jQuery AJAX in ASP.Net

Last Reply 5 months ago By dharmendr

Posted 6 months ago

few hurdles

 

1. using webmethod is secure i mean is it hackable easily or not i mean sql injection

2. i have two variables

 

var username: i need to fetch page.user.identity.name

var projetid= i need to pass query string value

 

3. on successfuly insert i have listview on page which i want to refresh data so it shows newly inserted values without refreshing page or my data to listview is coming from storeprocedure so storeprocedure can be refresh so it shows newly enter data somehow to refresh listview to show data without page refresh

Posted 5 months ago Modified on 5 months ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

HTML

Login.aspx

<asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
</asp:Login>

Login.aspx.cs

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    // Write code for login validation.
    FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
}

Login.aspx.vb

Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As AuthenticateEventArgs)
    FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
End Sub

Home.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
    else
    {
        Response.Redirect("~/CS.aspx?Country=India");
    }
}

Home.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.Page.User.Identity.IsAuthenticated Then
        FormsAuthentication.RedirectToLoginPage()
    Else
        Response.Redirect("~/CS.aspx?Country=India")
    End If
End Sub

Default.aspx

<div>
    <asp:ListView ID="lvCustomers" runat="server" GroupPlaceholderID="groupPlaceHolder1"
        ItemPlaceholderID="itemPlaceHolder1">
        <LayoutTemplate>
            <table cellpadding="0" id="tblCustomers" cellspacing="0">
                <tr>
                    <th>
                        CustomerId
                    </th>
                    <th>
                        Name
                    </th>
                    <th>
                        Country
                    </th>
                </tr>
                <asp:PlaceHolder runat="server" ID="groupPlaceHolder1"></asp:PlaceHolder>
            </table>
        </LayoutTemplate>
        <GroupTemplate>
            <tr>
                <asp:PlaceHolder runat="server" ID="itemPlaceHolder1"></asp:PlaceHolder>
            </tr>
        </GroupTemplate>
        <ItemTemplate>
            <td class="CustomerId">
                <%# Eval("CustomerId") %>
            </td>
            <td class="Name">
                <%# Eval("Name") %>
            </td>
            <td class="Country">
                <%# Eval("Country") %>
            </td>
        </ItemTemplate>
    </asp:ListView>
    <br />
    <br />
    <asp:Button Text="Insert" ID="btnInsert" runat="server" />
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        BindListView();
        $('#btnInsert').on('click', function () {
            var user = {};
            user.name = "<%= HttpContext.Current.User.Identity.Name%>"; // Get UserName from Identity.
            user.country = window.location.search.split('=')[1]; // Get QueryString Value.
            $.ajax({
                type: "POST",
                url: "Default.aspx/InsertCustomer",
                data: JSON.stringify(user),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == "Success") {
                        BindListView();
                    }
                    else { alert(response.d); }
                },
                failuer: function (response) { alert(response.d); },
                error: function (response) { alert(response.responseText); }
            });
            return false;
        });
    });

    function BindListView() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCustomers",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failuer: function (response) { alert(resposnse.d); },
            error: function (response) { alert(resposnse.responseText); }
        });
    };
    function OnSuccess(response) {
        var customers = response.d;
        var row = $("[id*=tblCustomers] tr:last-child").clone(true);
        var row1 = $("[id*=tbl1Customers] tr:last-child").clone(true);
        $("[id*=tblCustomers] tr").not($("[id*=tblCustomers] tr:first-child")).remove();
        $(customers).each(function () {
            var customer = $(this)[0];
            $(".CustomerId", row).html(customer.Name);
            $(".Name", row).html(customer.Name);
            $(".Country", row).html(customer.Country);
            $("[id*=tblCustomers]").append(row);
            row = $("[id*=tblCustomers] tr:last-child").clone(true);
        });
    }
</script>

Namespaces

C#

using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.Data;

VB.Net

Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Imports System.Data

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        // To Bind Dummy data to listView To get clone on Jquery OnSuccess method.
        this.BindDummyRow();
    }
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerId");
    dummy.Columns.Add("Name");
    dummy.Columns.Add("Country");
    dummy.Rows.Add();
    lvCustomers.DataSource = dummy;
    lvCustomers.DataBind();
}

[WebMethod]
public static List<Customer> GetCustomers()
{
    string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Customers");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    List<Customer> customers = new List<Customer>();
    con.Open();
    SqlDataReader sdr = cmd.ExecuteReader();
    while (sdr.Read())
    {
        customers.Add(new Customer
        {
            CustomerId = sdr["CustomerId"].ToString(),
            Name = sdr["Name"].ToString(),
            Country = sdr["Country"].ToString()
        });
    }

    con.Close();
    return customers;
}

[WebMethod]
public static string InsertCustomer(string name, string country)
{
    string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name,@Country)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    cmd.Parameters.AddWithValue("@Name", name);
    cmd.Parameters.AddWithValue("@Country", country);
    con.Open();
    int i = cmd.ExecuteNonQuery();
    con.Close();
    return i > 0 ? "Success" : "Fail";
}

public class Customer
{
    public string CustomerId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindDummyRow()
    End If
End Sub

Private Sub BindDummyRow()
    Dim dummy As DataTable = New DataTable()
    dummy.Columns.Add("CustomerId")
    dummy.Columns.Add("Name")
    dummy.Columns.Add("Country")
    dummy.Rows.Add()
    lvCustomers.DataSource = dummy
    lvCustomers.DataBind()
End Sub

<WebMethod>
Public Shared Function GetCustomers() As List(Of Customer)
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConStr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers")
    cmd.CommandType = CommandType.Text
    cmd.Connection = con
    Dim customers As List(Of Customer) = New List(Of Customer)()
    con.Open()
    Dim sdr As SqlDataReader = cmd.ExecuteReader()

    While sdr.Read()
        customers.Add(New Customer With {
            .CustomerId = sdr("CustomerId").ToString(),
            .Name = sdr("Name").ToString(),
            .Country = sdr("Country").ToString()
        })
    End While

    con.Close()
    Return customers
End Function

<WebMethod>
Public Shared Function InsertCustomer(ByVal name As String, ByVal country As String) As String
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConStr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("INSERT INTO Customers VALUES(@Name,@Country)")
    cmd.CommandType = CommandType.Text
    cmd.Connection = con
    cmd.Parameters.AddWithValue("@Name", name)
    cmd.Parameters.AddWithValue("@Country", country)
    con.Open()
    Dim i As Integer = cmd.ExecuteNonQuery()
    con.Close()
    Return If(i > 0, "Success", "Fail")
End Function

Public Class Customer
    Public Property CustomerId As String
    Public Property Name As String
    Public Property Country As String
End Class

Screenshot