最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to do postback Javascript, jquery - Stack Overflow

programmeradmin1浏览0评论
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>

Hi I have this code but I cant do postback for it, im not sure how to?

is it:

<script type="text/javascript"> 
        function CallServer() {
            __doPostBack('not sure what goes here','or here');
        }  
</script>

Then:

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/CallServer()/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>

My other script:

<script type="text/javascript">
    function confirm_delete()
{
  if (confirm("Are you sure you want to delete this comment?")==true)
    return true;
  else
    return false;
}
</script>

EDIT:

On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.IO;

public partial class UserProfileWall : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        //btn.Visible = false;
        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));
                        // this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
                        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.Style["clear"] = "both";
                        test1.Controls.Add(div);

                    }
                }
            }
        }
    }

    //protected void btnDelete_Click(object sender, EventArgs e)
    //{

    //    string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
    //    string[] idFragments = id.Split('_');
    //    id = idFragments[idFragments.Length - 1];

    //    //serverside code if confirm was pressed.
    //        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("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
    //            {
    //                cmd.ExecuteNonQuery();
    //            }
    //        }
    //        //PopulateWallPosts();

    //}

    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);
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
        string[] idFragments = id.Split('_');
        id = idFragments[idFragments.Length - 1];

        //serverside code if confirm was pressed.
        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("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        //PopulateWallPosts();
    }
}

On my asp html side i have:

<script type="text/javascript">
    function confirm_delete()
{
  if (confirm("Are you sure you want to delete this comment?")==true)
    return true;
  else
    return false;
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server" 
        CssClass="Btn" Text="delete" onclick="btn_Click"/>
    <asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3" 
        Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
     <asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px" 
        onclick="Button1_Click" />
    </p>
<p>
</p>
    <style type="text/css">
    img {border-width:0px; width:100px; height:100px;}
</style>
    <div id="test1" runat="server" />

    </div>

</asp:Content>

If you notice in my server side code I added this line:

div.Attributes.Add("onclick", "return confirm_delete();")

This works any time I click on my div the confirm_delete is called.

What I was trying to do with my asp button was when the div was clicked I could then call the onclick btnDelete_click.

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>

Hi I have this code but I cant do postback for it, im not sure how to?

is it:

<script type="text/javascript"> 
        function CallServer() {
            __doPostBack('not sure what goes here','or here');
        }  
</script>

Then:

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/CallServer()/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>

My other script:

<script type="text/javascript">
    function confirm_delete()
{
  if (confirm("Are you sure you want to delete this comment?")==true)
    return true;
  else
    return false;
}
</script>

EDIT:

On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.IO;

public partial class UserProfileWall : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        //btn.Visible = false;
        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));
                        // this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
                        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.Style["clear"] = "both";
                        test1.Controls.Add(div);

                    }
                }
            }
        }
    }

    //protected void btnDelete_Click(object sender, EventArgs e)
    //{

    //    string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
    //    string[] idFragments = id.Split('_');
    //    id = idFragments[idFragments.Length - 1];

    //    //serverside code if confirm was pressed.
    //        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("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
    //            {
    //                cmd.ExecuteNonQuery();
    //            }
    //        }
    //        //PopulateWallPosts();

    //}

    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);
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
        string[] idFragments = id.Split('_');
        id = idFragments[idFragments.Length - 1];

        //serverside code if confirm was pressed.
        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("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        //PopulateWallPosts();
    }
}

On my asp.net html side i have:

<script type="text/javascript">
    function confirm_delete()
{
  if (confirm("Are you sure you want to delete this comment?")==true)
    return true;
  else
    return false;
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server" 
        CssClass="Btn" Text="delete" onclick="btn_Click"/>
    <asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3" 
        Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
     <asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px" 
        onclick="Button1_Click" />
    </p>
<p>
</p>
    <style type="text/css">
    img {border-width:0px; width:100px; height:100px;}
</style>
    <div id="test1" runat="server" />

    </div>

</asp:Content>

If you notice in my server side code I added this line:

div.Attributes.Add("onclick", "return confirm_delete();")

This works any time I click on my div the confirm_delete is called.

What I was trying to do with my asp.net button was when the div was clicked I could then call the onclick btnDelete_click.

Share Improve this question edited Sep 14, 2015 at 19:50 Kristijan Iliev 4,98710 gold badges30 silver badges51 bronze badges asked Mar 30, 2011 at 19:20 G GrG Gr 6,08020 gold badges94 silver badges184 bronze badges 5
  • The code if (xyz == true) { return true; } else { return false; } seems a little redundant. Wouldn't return xyz; be cleaner and less error-prone? – Dancrumb Commented Mar 30, 2011 at 19:48
  • Garrith: show us the complete aspx context. Are you using UpdatePanels? Does it work if you simply write OnClientClick="javascript: return confirm("Are you sure you want to delete this comment?");"? – Tim Schmelter Commented Mar 30, 2011 at 20:02
  • updated hope ive explain'd it better – G Gr Commented Mar 30, 2011 at 20:16
  • I'n not sure why the handler is not called - first i thought it was because you are clearing the controls of the DIV on every postback, but the button is not part of it. But if you only want to call its handler you could set it's style display to none and call __doPostBack(see my answer) to call the Button-handler from the div's click event(after confirmation). – Tim Schmelter Commented Mar 30, 2011 at 20:25
  • Don't add the onclick handler as an attribute. Use OnClick and OnClientClick in the aspx file. The server will wrap those handlers and set the onclick for you. – Dave Rager Commented Mar 30, 2011 at 20:28
Add a comment  | 

4 Answers 4

Reset to default 8
OnClientClick="return confirm_delete();"

That's it...

Edit: __doPostBack works also...

OnClientClick="if(confirm('delete?'))__doPostBack('btn',''); else return false;"

If you really are wanting to manually call __doPostBack(), the first parameter is the .NET generated name for the control. This can be gotten on the server side using Control.ClientID. The second parameter is any extra data that should be passed along in the request. Most of the time I see this field is an empty string.

__doPostBack('ctl100$controlName$id','');

The controlName is the .NET class name of the control I believe, id is the ID you gave the control. To be sure, view the source of the page after it has been rendered in the browser and search for calls to __doPostBack and see how they are formatted.

By a postback in this case do you want to just refresh the page? If so then it would just be:

    location.reload();

in your case:

    <script type="text/javascript">
        function CallServer() 
        {
               location.reload();
        }
    </script>

Demo (A button click prompts the user to confirm - if they choose Yes, a post back occurs)

See demo here!

One method, not the best for sure: Add a button into an update panel and set it invisble. Then call click() method of the button.

Somthing like this:

document.getElementById('button').click();
发布评论

评论列表(0)

  1. 暂无评论