如何在js模式中显示编辑数据 [英] How do I show my edit data in a js modal

查看:106
本文介绍了如何在js模式中显示编辑数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用代码实现crud操作,我遇到了问题,当我点击我的编辑[linkBut​​ton]时,页面只是刷新没有任何反应。添加新用户按钮工作正常





这是我的HTML代码



<%@ Page Language =C#AutoEventWireup =trueCodeFile =Default.aspx.csInherits =_ Default%> 

<!DOCTYPE html PUBLIC - // W3C // DTD XHTML 1.0 Transitional // ENhttp://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 =stylesheettype =text / css/>
< / head>
< body>
< form id =form1runat =server>
< div>

< asp:Button ID =btnAddUsersrunat =serverText =Add New Users/>
< br />< br />

< div class =modal>
< div class =modal-content>
< span class =close>×< / span>
< p>添加修改记录< / p>< hr />
< table>
< tr>
< td>
< asp:HiddenField ID =hfUserIdrunat =server/>
< / td>
< td colspan =2>

< / td>
< / tr>
< tr>
< td>
< asp:Label ID =Label1runat =serverText =Name>< / asp:Label>
< / td>
< td colspan =2>
< asp:TextBox ID =txtNamerunat =server>< / asp:TextBox>
< / td>
< / tr>
< tr>
< td>
< asp:Label ID =Label2runat =serverText =Email>< / asp:Label>
< / td>
< td colspan =2>
< asp:TextBox ID =txtEmailrunat =server>< / asp:TextBox>
< / td>
< / tr>
< tr>
< td>
< asp:Label ID =Label3runat =serverText =Level>< / asp:Label>
< / td>
< td colspan =2>
< asp:DropDownList ID =ddlLevelrunat =server>
< asp:ListItem> Level 2< / asp:ListItem>
< asp:ListItem> Level 3< / asp:ListItem>
< asp:ListItem>等级4< / asp:ListItem>
< / asp:DropDownList>
< / td>
< / tr>
< tr>
< td>

< / td>
< td colspan =2>
< asp:Button ID =btnSaverunat =serverText =Saveonclick =btnSave_Click/>
< asp:Button ID =btnClearrunat =serverText =Clearonclick =btnClear_Click/>
< / td>
< / tr>
< tr>
< td>

< / td>
< td colspan =2>
< asp:Label ID =lblSuccessMessagerunat =serverText =ForeColor =Green>< / asp:Label>
< / td>
< / tr>
< / table>
< / div>
< / div>


< asp:GridView ID =gvUsersrunat =serverAutoGenerateColumns =falseEmptyDataText =没有插入Recodrs ...>
< Columns>
< asp:TemplateField>
< ItemTemplate>
< asp:LinkBut​​ton ID =lnkViewCommandArgument ='<%#Bind(userId)%>'OnClick =lnkView_ClickOnClientClick =return modal('modal','close', 'lnkView')runat =server>编辑< / asp:LinkBut​​ton>
< / ItemTemplate>
< / asp:TemplateField>
< asp:TemplateField>
< ItemTemplate>
< asp:LinkBut​​ton ID =lnkDeleteCommandArgument ='<%#Bind(userId)%>'OnClick =lnkDelete_Clickrunat =server>删除< / asp:LinkBut​​ton>
< / ItemTemplate>
< / asp:TemplateField>
< asp:BoundField DataField =userNameHeaderText =userName/>
< asp:BoundField DataField =userEmailHeaderText =userEmail/>
< asp:BoundField DataField =userLevelHeaderText =userLevel/>
< / Columns>
< / asp:GridView>

< / div>
< script type =text / javascriptsrc =main.js>< / script>
< / form>
< / body>
< / html>





这是我的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);



这是我的c#代码



使用System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControls;
使用System.Data.SqlClient;
使用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);

//在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();
尝试
{
da.Fill(dt);
gvUsers.DataSource = dt;
gvUsers.DataBind();
con.Close();
}
catch(Exception ex){
Response.Write(ex.Message);
}
}
}

//清除所有输入字段
void clear(){
lblSuccessMessage.Text = txtEmail.Text = txtName.Text =;
ddlLevel.Text =等级2;
hfUserId.Value =;
txtName.Focus();
btnSave.Text =保存;
}
protected void btnClear_Click(object sender,EventArgs e)
{
clear();
}
protected void lnkView_Click(object sender,EventArgs e){
int conId = Convert.ToInt32((sender as LinkBut​​ton).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();
尝试
{
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 =更新;
}
catch(Exception ex){
Response.Write(ex.Message);
}
}
}
protected void lnkDelete_Click(object sender,EventArgs e)
{
int conId = Convert.ToInt32((发送者为LinkBut​​ton) .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 =已删除的记录;
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 +,您的记录已成功保存...;
display();
}
else {
lblSuccessMessage.Text = txtName.Text +,您的记录已成功更新......;
display();
}
}
catch(Exception ex){
Response.Write(ex.Message);
}
}
}
}





我尝试了什么:



我试过在我的后端调用模态show函数但它仍然没有产生任何结果,我试着通常在脚本中调用它的函数标签,它仍然无法正常工作

解决方案

一个 LinkBut​​ton 会导致页面回发,这就是你的模态创建的原因从JavaScript函数将丢失。尝试做这样的事情:



 OnClientClick =  < span class =code-string> modal('modal','close','lnkView'); return false; 





返回false; 将阻止页面在执行JavaScript函数时进行回发。



另外,您可能需要考虑查看AJAX ModalPopup控件,因为它允许您在服务器上触发模式而无需执行任何客户端代码。例如: https:/ /www.aspsnippets.com/Articles/How-to-edit-GridView-Row-using-AJAX-Modal-Popup-Extender-in-ASPNet.aspx [ ^ ]


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

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

解决方案

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:

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[^]


这篇关于如何在js模式中显示编辑数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆