Can any one help me with this code:
ASP:
<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;
}
}
Page Load code behind:
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);
}
Code Behind:
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("   " + "{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);
}
}
}
}
}
There are quite a few problems with your code. First, the argument to a javascript function must be a legal variable name. You are using a property reference on a variable. Second, I suspect that you may be using numeric ids for your DIV ids. Note that they have to start with a letter and must be unique. It’s possible yours are this way, but given that they seem to refer to comment ids it seems likely that they may be fully numeric. Third, you probably should be passing back the id of the control in the __EVENTTARGET parameter, that’s what the frame work expects. Fourth, just return false if it isn’t confirm. That will cancel the normal action. If it is confirmed, you’re doing the postback manually and still want the normal action cancelled. Note that it is a full postback, not AJAX so you should return a full page. Fifth, you need to put quotes around the id when you write out the javascript. Lastly, there are much better ways to do this, but it would take more than just one answer to show you how. Look for information on using AJAX with web forms.
ASPX
Page Load
Code-behind