开发者

Utterly stuck, to short to explain in a title, covers c# asp.net controls and html code and a little javascript

Guys i think im lost in my own code, I will try explain exactly what im trying to do, I just hope you can follow and I hope there is a simple solution.

My code creates dynamic content i.e the user types into a textbox and when he hits the post message button his message is saved to a mysql database, that initial button click also sends it back to the original code (PopulateWallPosts) which repopulates the html content.

When the data is saved and populated and repopulated the content from the database is stored in a div on the client side.

What I tryed to do with the code below was find a way I could delete the individual divs so I assigned the div ids to idWallPosting which is the PK and auto increment number of the content saved from the textbox when the user types something.

So that all worked out fine I now have div which display the content i wish from my database i have nice css styling applied but I have one big problem. I cant find a way to delete the divs AND content from my database.

I tryed to tie an asp button to some javascript at the same time tying it to the div as you will see in the code so when some one clicks on the div it will ask if you want to delete it hoping that when the user hits ok it would fire the asp button onclick event but it didnt. Im not sure if I went about it the correct way as the posts from my previous post didnt help me.

So im stuck, I have 0 experience with ajax or json so that cant help me. The only other way I can think of if its possible is turning the div into the same format as a button click event so when the div is clicked it will fire the javascript and an onclick event?

Code behind:

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();
  开发者_如何学C          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 " + "{0}", reader.GetString(1))));
                        div.Attributes.Add("onclick", "return confirm_delete();");

                        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);
    }
    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();
    }
}

ASP html code:

  <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>

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

So atm im pretty much stuck, if only I could call server side code upon return true; in my javascript I would be happy as larry but I cant find a way to do it?


This might not be your root issue but something you might want to change up change your javascript function to this: (this isn't the part that might fix it just a simplification)

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

Now with that simplified change you asp.net button to this:

<asp:Button ID="btn" OnClientClick="return confirm_delete();" OnClick="btnDelete_Click" runat="server" Text="delete"/>

This will ensure that it always has a return value either true or false. If it comes back true it should continue on and initiate a postback if it is false it should not postback.

There was a lot there so let me know if I missed the meat of your issue.

EDIT: missed the part where you need to click the button programatically when you click the div. You can add this javascript function to the page. Note it must be on that page either the head or body but it will not work if you abstract it to an external js file.

function clickTheButton(){    
       document.getElementById('<%= btn.ClientID %>').click();
}

I used the "<%=" tags in case the control nesting hierarchy changes which would change the rendered id of the button.

So putting a call to the awesomely named "clickTheButton" function (I am horrible at naming functions so you will want to change this to a better name) in the onclick handler of the div should click the button via javascript which would fire off the other stuff.


Change your javascript function to this: (adding your own true==true logic is unnecessary)

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

And change your OnClientClick attribute to this:

OnClientClick="return confirm_delete()"

The client-side ASP.NET postback functionality will take care of the rest

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜