【问题标题】:store div id as string send to javascript then grab after postback将 div id 存储为字符串发送到 javascript,然后在回发后抓取
【发布时间】:2023-03-26 16:51:01
【问题描述】:

谁能帮我解决这个代码:

平均售价:

    <script type="text/javascript">
        function confirm_delete(div.ID)// problem here{
            if (confirm('Are you sure you want to delete?')) {
                __doPostBack('DivClicked', div.ID);
// not sure if javascript will pick up on the string from server side code
            }
            else {
                return false;
            }
        }

页面加载代码后面:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            //It is a postback so check if it was by div click
            string target = Request["__EVENTTARGET"];
            if (target == "DivClicked")
            {
                String.Format(div.ID) = Request["__EVENTARGUMENT"];
                // problem converting div.ID from Javascript to string (because of the dot)

                Response.Write(String.Format(div.ID));
               // same problem here
            }
        }
        string theUserId = Session["UserID"].ToString();
        PopulateWallPosts(theUserId);
    }

代码背后:

               while (reader.Read())
                {

                    System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                    div.Attributes["class"] = "test";


                    div.ID = String.Format("{0}", reader.GetString(0));
                    Convert.ToString(div.ID);
                    //store the div id as a string
                    Image img = new Image();
                    img.ImageUrl = String.Format("{0}", reader.GetString(2));
                    img.AlternateText = "Test image";

                    div.Controls.Add(img);
                    div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp&nbsp;" + "{0}", reader.GetString(1))));
                    div.Attributes.Add("onclick", "return confirm_delete(" + div.ID + ");");
                    // send the div id to javascript, not sure this line will work
                    div.Style["clear"] = "both";
                    test1.Controls.Add(div);

                }
            }
        }
    }
}

【问题讨论】:

    标签: c# javascript asp.net html


    【解决方案1】:

    加里斯,

    就像你上一个问题一样,你希望你的 javascript 看起来像:

    <script type="text/javascript">
    function clickTheDiv() {
    
        var Sender = window.event.srcElement;
    
        if(confirm("are you sure?"))
        {
                __doPostBack('DivClicked', Sender.ID)
        }
    }
    </script>
    

    ...为您的 div 执行此操作:

    div.Attributes.Add("onclick", "clickTheDiv();"
    //(with all your other work around this)
    

    您应该能够在这里解决您需要的其余部分。

    干杯,

    CEC

    【讨论】:

    • 这是调用函数的元素,在本例中是您感兴趣的实际
    【解决方案2】:

    您的代码存在很多问题。首先,javascript 函数的参数必须是合法的变量名。您正在对变量使用属性引用。其次,我怀疑您可能正在为您的 DIV id 使用数字 id。请注意,它们必须以字母开头,并且必须是唯一的。您的可能是这种方式,但鉴于它们似乎指的是评论 ID,它们似乎可能是完全数字的。第三,您可能应该在 __EVENTTARGET 参数中传回控件的 id,这正是框架所期望的。第四,不确认就返回false。这将取消正常操作。如果确认,您正在手动执行回发,但仍希望取消正常操作。请注意,这是一个完整的回发,而不是 AJAX,因此您应该返回一个完整的页面。第五,当你写出 javascript 时,你需要在 id 周围加上引号。最后,有很多更好的方法可以做到这一点,但要告诉你如何做,需要的不仅仅是一个答案。查找有关在 Web 表单中使用 AJAX 的信息。

    ASPX

    function confirm_delete(id) {
        if (confirm('Are you sure you want to delete?')) {
            __doPostBack(id,'');
        }
        return false;
      }
    

    页面加载

       if (Page.IsPostBack)
        {
            string target = Request["__EVENTTARGET"];
            if (target.StartsWith("comment"))
            {
                // remove comment string to get actual id
                string id = target.Replace( "comment", "" );
    
                // now do something with the id, like delete the comment?
            }
        }
        // finish the page
        string theUserId = Session["UserID"].ToString();
        PopulateWallPosts(theUserId);
    

    代码隐藏

     while (reader.Read())
     {
    
        var div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
        div.Attributes["class"] = "test";
    
    
        div.ID = String.Format("comment{0}", reader.GetString(0));
    
        Image img = new Image();
        img.ImageUrl = String.Format("{0}", reader.GetString(2));
        img.AlternateText = "Test image";
    
        div.Controls.Add(img);
        div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp&nbsp;" + "{0}", reader.GetString(1))));
        // the single quotes in the line below are critical
        div.Attributes.Add("onclick", "return clickTheButton('" + div.ID + "');");
        div.Style["clear"] = "both";
        test1.Controls.Add(div);
    

    【讨论】:

    • 对不起,你一开始很出色,然后你添加这个:如果(target.StartsWith("comment")) { // remove comment string to get actual id string id = target.Replace( "comment", "" );
    • 真的不知道 target.startswith 是什么?当你说替换时,我只是用 id 替换两个 cmets 吗?
    • 对不起,我应该提到的是,div id 是数字,它是引用我的数据库 cmets 的唯一方法
    • @Garrith -- 请注意我如何将字符串“comment”添加到后面代码中的数字 id 以使其成为合法的 HTML 元素 id。 StartsWith 是一个字符串函数,用于测试字符串是否以参数开头,即 id 是否以“comment”开头。我使用字符串替换功能从 id 中删除“comment”字符串,以使 id 恢复正常形式。如果您需要它作为数字,请在获取 id 作为字符串后使用var commentID = int.Parse(id);。然后使用它从数据库中删除项目。
    【解决方案3】:

    Javascript wont do a postback from c# code in asp.net

    这个问题的答案:

        <script type="text/javascript">
            function confirm_delete(id){
                if (confirm('Are you sure you want to delete?')) {
                    __doPostBack('DivClicked', id);
                }
                else {
                    return false;
                }
            }
    </script>
    

    后面的代码

    public partial class UserProfileWall : System.Web.UI.Page
    {
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                //It is a postback so check if it was by div click (NOT WORKING because the javascript isnt posting back)
                string target = Request["__EVENTTARGET"];
                if (target == "DivClicked")
                {
                    string id = Request["__EVENTARGUMENT"];
                    //Call my delete function passing record id
                    Response.Write(String.Format(id)); //just a test 
                }
            }
            string theUserId = Session["UserID"].ToString();
            PopulateWallPosts(theUserId);
        }
        private void PopulateWallPosts(string userId)
        {
    
            using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
            {
                cn.Open();
                using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
                {
                    //("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
                    using (OdbcDataReader reader = cmd.ExecuteReader())
                    {
                        test1.Controls.Clear();
    
                        while (reader.Read())
                        {
    
                            System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                            div.Attributes["class"] = "test";
    
    
                            div.ID = String.Format("{0}", reader.GetString(0));
                            string id = Convert.ToString(div.ID);
                            //store the div id as a string
                            Image img = new Image();
                            img.ImageUrl = String.Format("{0}", reader.GetString(2));
                            img.AlternateText = "Test image";
    
                            div.Controls.Add(img);
                            div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp&nbsp;" + "{0}", reader.GetString(1))));
                            div.Attributes.Add("onclick", "return confirm_delete(" + id + ");");
                            // send the div id to javascript
                            div.Style["clear"] = "both";
                            test1.Controls.Add(div);
    
                        }
                    }
                }
            }
        }
    
    
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            string theUserId = Session["UserID"].ToString();
            using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
            {
                cn.Open();
                using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
            PopulateWallPosts(theUserId);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多