Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So I am trying to implement crud operations with code only and I am experiencing a problem, when I click my Edit [linkButton] nothing happens the page just refreshes. The Add New user button works perfectly


Here is my html code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>ASP CRUD</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="btnAddUsers" runat="server" Text="Add New Users" />
        <br /><br />

        <div class="modal">
            <div class="modal-content">
                <span class="close">×</span>
                <p>Add Edit Records</p><hr />
                <table>
                    <tr>
                        <td>
                            <asp:HiddenField ID="hfUserId" runat="server" />
                        </td>
                        <td colspan="2">
                    
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
                        </td>
                        <td colspan="2">
                            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label2" runat="server" Text="Email"></asp:Label>
                        </td>
                        <td colspan="2">
                            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label3" runat="server" Text="Level"></asp:Label>
                        </td>
                        <td colspan="2">
                            <asp:DropDownList ID="ddlLevel" runat="server">
                               <asp:ListItem>Level 2</asp:ListItem>
                               <asp:ListItem>Level 3</asp:ListItem>
                               <asp:ListItem>Level 4</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                    
                        </td>
                        <td colspan="2">
                            <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
                            <asp:Button ID="btnClear" runat="server" Text="Clear" onclick="btnClear_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                    
                        </td>
                        <td colspan="2">
                            <asp:Label ID="lblSuccessMessage" runat="server" Text="" ForeColor="Green"></asp:Label>
                        </td>
                    </tr>
                </table>
            </div>
        </div>


        <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" EmptyDataText="No Recodrs have been Inserted...">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkView" CommandArgument='<%# Bind("userId") %>' OnClick="lnkView_Click" OnClientClick="return modal('modal','close','lnkView')" runat="server">Edit</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDelete" CommandArgument='<%# Bind("userId") %>' OnClick="lnkDelete_Click" runat="server">Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="userName" HeaderText="userName" />
                <asp:BoundField DataField="userEmail" HeaderText="userEmail" />
                <asp:BoundField DataField="userLevel" HeaderText="userLevel" />
            </Columns>
        </asp:GridView>
    
    </div>
    <script type="text/javascript" src="main.js"></script>
    </form>
</body>
</html>


Here is my Javascript code
JavaScript
function modal(_modal,_span,_btnModal) {
    var modal = document.getElementsByClassName(_modal)[0];
    var span = document.getElementsByClassName(_span)[0];
    var btnModal = document.getElementById(_btnModal);

    btnModal.onclick = function () {
        modal.style.display = "block";
        return false;
    }

    span.onclick = function () {
        modal.style.display = "none";
    }

    window.onclick = function (event) {
        if (event.target === modal) {
            modal.style.display = "none";
        }
    }
}

modal("modal","close","btnAddUsers");

Here is my c# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            display();
        }
    }

    SqlConnection con = new SqlConnection(@connection_string);

    //Display All Records on the GridView
    void display() {
        if (con.State == ConnectionState.Closed) {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("ViewAllRecords",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            try
            {
                da.Fill(dt);
                gvUsers.DataSource = dt;
                gvUsers.DataBind();
                con.Close();
            }
            catch (Exception ex) {
                Response.Write(ex.Message);
            }
        }
    }

    //Clear All Input fields
    void clear() {
        lblSuccessMessage.Text = txtEmail.Text = txtName.Text = "";
        ddlLevel.Text = "Level 2";
        hfUserId.Value = "";
        txtName.Focus();
        btnSave.Text = "Save";
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        clear();
    }
    protected void lnkView_Click(object sender, EventArgs e) {
        int conId = Convert.ToInt32((sender as LinkButton).CommandArgument);
        if (con.State == ConnectionState.Closed) {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("ViewById",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            hfUserId.Value = conId.ToString();
            da.SelectCommand.Parameters.AddWithValue("@userId",conId);
            DataTable dt = new DataTable();
            try
            {
                da.Fill(dt);
                txtName.Text = dt.Rows[0]["userName"].ToString();
                txtEmail.Text = dt.Rows[0]["userEmail"].ToString();
                ddlLevel.Text = dt.Rows[0]["userLevel"].ToString();
                btnSave.Text = "Update";
            }
            catch (Exception ex) {
                Response.Write(ex.Message);
            }
        }
    }
    protected void lnkDelete_Click(object sender, EventArgs e)
    {
        int conId = Convert.ToInt32((sender as LinkButton).CommandArgument);
        if (con.State == ConnectionState.Closed) {
            con.Open();
            SqlCommand command = new SqlCommand("DelRecords",con);
            command.CommandType = CommandType.StoredProcedure;
            hfUserId.Value = conId.ToString();
            command.Parameters.AddWithValue("@userId",Convert.ToInt32(hfUserId.Value));
            try
            {
                command.ExecuteNonQuery();
                lblSuccessMessage.Text = "Records Deleted";
                con.Close();
                clear();
                display();
            }
            catch (Exception ex) {
                Response.Write(ex.Message);
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed) {
            con.Open();
            SqlCommand command = new SqlCommand("InsUpdRecords",con);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@userId",hfUserId.Value==""?0:Convert.ToInt32(hfUserId.Value));
            command.Parameters.AddWithValue("@userName",txtName.Text.Trim());
            command.Parameters.AddWithValue("@userEmail",txtEmail.Text.Trim());
            command.Parameters.AddWithValue("@userLevel",ddlLevel.SelectedItem.ToString());
            try
            {
                command.ExecuteNonQuery();
                con.Close();
                if (hfUserId.Value == "0")
                {
                    lblSuccessMessage.Text = txtName.Text + ",your Records have been successfully saved...";
                    display();
                }
                else {
                    lblSuccessMessage.Text = txtName.Text + ",your Records have been succesfully Updated...";
                    display();
                }
            }
            catch (Exception ex) {
                Response.Write(ex.Message);
            }
        }
    }
}


What I have tried:

I have tried calling the modal show function in my back-end but it still yielded no results, I tried calling it the function normally in script tags and it still didn't work
Posted
Updated 20-Dec-18 15:18pm
v3
Comments
PRAKASH9 19-Dec-18 2:08am    
Have you done with debug or not? Just hit F12 and put your debug point in debbuger tab inside modal function so you can easily identify where is your code crashed.
Judah.zama 19-Dec-18 2:51am    
I have tried but it gives me nothing
PRAKASH9 19-Dec-18 4:48am    
you have to debug like this
https://prnt.sc/lww7jw

I just think your code will be crashed from here

var btnModal = document.getElementById(_btnModal);

You have passed 'lnkView' argument like below

<asp:LinkButton ID="lnkView" CommandArgument='<%# Bind("userId") %>' OnClick="lnkView_Click" OnClientClick="return modal('modal','close','lnkView')" runat="server">Edit

but your LinkButton is inside gridview so id of that button changed and you cann't get in modal function. so i think your code will be crashed from
_btnModal

1 solution

A LinkButton causes a page to postback that's why your modal created from a JavaScript function will be lost. Try to do something like this instead:

JavaScript
OnClientClick="modal('modal','close','lnkView');return false;"


The return false; will prevent the page to do a postback while executing your JavaScript function.

Also, you may want to consider looking at AJAX ModalPopup control as it allows you to trigger the modal at the server without doing any client-side code. For example: https://www.aspsnippets.com/Articles/How-to-edit-GridView-Row-using-AJAX-Modal-Popup-Extender-in-ASPNet.aspx[^]
 
Share this answer
 
Comments
Judah.zama 25-Dec-18 15:36pm    
I tried that Vincent and it didnt work

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900