MenuItem call javascript function - c#

Dynamically building menu items and need to call a javascript function from one of them.
function popWin(url) {
var winHandle = window.open(url, '_blank', 'width=1000,height=700,resizable=yes,top=5,left=5,scrollbars=yes,status=yes');
}
<asp:Menu ID="Menu1" runat="server" StaticDisplayLevels="8" RenderingMode="List" OnMenuItemClick="Menu1_MenuItemClick" CssClass="menu" Width="150px">
</asp:Menu>
The code behind:
string url = "/somepage.aspx";
MenuItem child = new MenuItem();
child.Text = "Some Text";
child.NavigateUrl = "javascript:popWin('" + url + "');";
//child.NavigateUrl = "javascript:window.open('somepage.aspx');";
Menu1.Items[1].ChildItems.Add(child);
Just having some trouble calling the javascript function.
The window.open will work but an extra page opens and I need more control over the window opening.
The reason this needs to be done this way is there's an iFrame on the page that's loading different pages. The RegisterStartupScript was being used in the Menu1_MenuItemClick event but it was refreshing the source of the iFrame.
Thanks for any suggestions.
UPDATE
Trying to go another route on this but just not working right:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin(" + win + ");";
string text = "<span style='cursor:pointer;' onclick='" + script + "'>Some Text</span>";
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);

After coming back to this problem and testing a span tag in html with an onclick event, the problem was simply a bit of syntax:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin('" + win + "');";
string text = "<span style=\"cursor:pointer;\" onclick=\"" + script + "\">Some Text</span>";
//Below is how it should render
//<span style="cursor:pointer;" onclick="popWin('/SomePage.aspx');">Some Text</span>
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);
Thought I would post this just in case anyone else runs into the same issue.

Related

PostBackUrl being overwritten in my jquery .load panel

In my C# web application, I have one page with a panel control:
ViewTask.aspx
<asp:Panel ID="panelImageThumbnails" runat="server" Style="width: 100%;">
This panel gets filled using jQuery .load with page ThumbnailPanel.aspx
<script type="text/javascript">
$(window).load(function () {
LoadThumbnails();
});
function LoadThumbnails() {
$("#panelImageThumbnails").empty();
var imglink = "<span style='text-align: center; align-content:center'>Getting thumbnails, please wait!<br><br><img src='Images/loader.gif'><br><br></span>";
$("#panelImageThumbnails").append(imglink);
$('#panelImageThumbnails').load('ThumbnailPanel.aspx').hide().fadeIn(1000);
return false;
}
</script>
Inside ThumbnailPanel.aspx, I query a table for a list of images and then loop over the DataTable and write them each to another panel each as ImageButtons
//Add a new image button to the thumbnail panel
ImageButton newImageButton = new ImageButton();
newImageButton.ID = "ib_" + row["Screenshot_ID"].ToString();
newImageButton.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
newImageButton.PostBackUrl = "ViewImage.aspx?fileName=" + row["Screenshot_ID"].ToString() + ".png";
newImageButton.OnClientClick = "target='_blank'";
newImageButton.CssClass = "thumbnailButton";
newImageButton.ToolTip = row["Screenshot_Created"].ToString() + "(" + row["Screenshot_CreatedBy"].ToString() + ")";
newImageButton.AlternateText = row["Screenshot_Title"].ToString();
panelUploadedImageThumbnails.Controls.Add(new LiteralControl("<table border='1' style='border-collapse: collapse;' class='inlineTable'><tr><td style='font-size:7pt;'>" + row["Screenshot_Title"].ToString() + "</td></tr><tr><td>"));
panelUploadedImageThumbnails.Controls.Add(newImageButton);
panelUploadedImageThumbnails.Controls.Add(new LiteralControl("</td></tr></table>"));
I set the PostBackUrl to page "ViewImage" and feed in the Screenshot_ID. This page converts the image to a bytearray and prints it to the screen.
ThumbnailPanel.aspx works perfectly on its own. But when it's loaded into panelImageThumbnails during the jQuery .load inside ViewTask.aspx all of the hyperlinks point to ThumbnailPanel.aspx instead of ViewImage.aspx.
Any idea how I can fix my desired PostBackUrl from being ignored?

Accessing a "HtmlGenericControl" from a Master Page where the control was created dynamically

I have a master page "default.master" and a content page "Store.aspx", each with their own code-behind page. In the code-behind of the master page, I am dynamically creating a label with some text in it. I want to look up the text of the label in the code-behind page for the 'Store.aspx.cs' but my code is returning 'null' controls...
In my default.master.cs on page load:
<label runat=\"server\" id=\"displayname\"><a href='MyAvatar.aspx'>" + displayName + "</a></label>
In my Store.aspx.cs on page load:
HtmlGenericControl dName = (HtmlGenericControl)Master.FindControl("displayName");
if (dName != null)
Debug.Print("dName: " + dName.InnerText);
This does NOT work... However, if I put a label directly in the default.master page like this:
<label runat="server" id="displayName">TEST</label>
Then when i load the Store.aspx, I clearly see in my Debug Output:
dName: TEST
I really need the label to be created dynamically and also need to be able to access the content of the label not only from the Store.aspx.cs but from 2 other pages as well (and potentially more in the future). Any ideas??
EDIT:
I just wanted to note that the dynamically created label is part of a larger element... The label is inside a table cell, inside a table row, inside a table, all of which is inside a literal control... What the heck, why not paste the whole thing here huh? (Label is in the 4th line)
userCP.Text = "<table width=100% border=0 cellpadding=0 cellspacing=0>" +
"<tr><td colspan=4 style=\"font-size: large\"><center><b>Welcome,</b></center></td></tr>" +
"<tr style=\"height: 5px; \"><td colspan=4></td></tr>" +
"<tr><td colspan=4><center><label runat=\"server\" id=\"displayname\"><a href='MyAvatar.aspx'>" + displayName + "</a></label></center></td></tr>" +
"<tr style=\"height: 5px; \"><td colspan=4></td></tr>" +
"<tr><td colspan=4><hr/></td></tr>" +
"<tr><td>" + leaderLink + "</td><td width=100% id=\"userCP_bones\" style=\"text-align:right; \">" + bones + "</td><td style=\"text-align:left;\"><b>/</b><a href='Store.aspx?SC=Acct' title='Click to upgrade your wallet!'>" + maxBones + "</a></td><td><center><img src='images/bone.png' alt='Bones' align='right' style=\"vertical-align:middle\"/></center></td></tr>" +
"<tr><td></td><td></td><td id='CartCount' style=\"text-align:right; text-decoration: underline; cursor:pointer; \"><a href='Checkout.aspx'>" + itemCount + "</a></td><td width=10%><center><a href='Checkout.aspx'><img src='images/cart.png' onmouseover=\"this.src='images/cart_h.png'\" onmouseout=\"this.src='images/cart.png'\" height='24' width='24' alt='Cart' align='right' style=\"vertical-align:middle; border:none\"/></a></center></td></tr>" +
"</table>";
EDIT:
Based on the first answer given, instead of a literal control for "userCP", I turned that into an ASP table and add rows/cells in the code-behind:
//Row for display name
TableRow r = new TableRow();
userCP.Rows.Add(r);
TableCell c = new TableCell();
r.Cells.Add(c);
c.ColumnSpan = 4;
Label l = new Label();
l.Text = "<center><a href='MyAvatar.aspx'>" + displayName + "</a></center>";
l.ID = "displayName";
c.Controls.Add(l);
My store.aspx.cs is still returning null when doing:
Debug.Print("Name: " + Master.FindControl("displayName"));
Even if I cast the lookup:
(HtmlGenericControl)Master.FindControl("displayName")
(Label)Master.FindControl("displayName")
You cannot add server-side control by directly manipulating page markup from code, because page is already created by that time. If you want to create controls dynamically and then access them from server-side code you need to add them to Controls collection.
You have to build your ASP.Net HtmlTable server-side control (including HtmlTableRow and table HtmlTableCell and all the related controls) thru actual server-side code and add the resulting table to the userCP with something like userCP.Controls.Add(myCreatedTable)
Just to clean up, clarify, and centralize the answers and comments:
It doesn't matter if I use the LiteralControl or the Asp:Table, the 'displayName' I need is now stored as a global variable in the default.master.cs file:
string displayName = "Guest";
public string dName()
{
return displayName;
}
And can be looked up from any content page using:
//Make sure the user has an account
string dName = ((_default)Master).dName();
if (dName == "Guest")
{
LiteralStoreHeader.Text = "<center><b>We're Sorry!</b><br/>You must have an Avatar account to view this page.</center>";
return;
}
However, if I really do need to pull the info from a cell in the table without storing it as a variable on the default.master.cs page, I can also do that by using the ASP Table instead of the LiteralControl and then looking up the id of the Label:
Master Code File:
Label l;
public string FOO()
{
return l.Text;
}
protected void Page_Load(object sender, EventArgs e)
{
l = new Label();
l.Text = "Bar";
}
Content Code File:
string dName = ((_default)Master).FOO();

How to add an image to an asp.net link button programatically

I have an ASP.NET link button that I need to add both text and an image to I thought I would be able to just add the image to the button using Controls.Add but no dice.
Here is what I have so far:
foreach (var entity in metadata.Meta.Where(e => e.ReportableObject == true))
{
LinkButton lb = new LinkButton();
string iconpath = "~/images/search/" + entity.ClassName + ".png";
lb.CssClass = "entityIcon";
lb.Controls.Add(new Image { ImageUrl = iconpath , CssClass = "imgSize"});
lb.Text = entity.ClassName;
entityHolder.Controls.Add(lb);
}
When the control renders I see the text but I'm not even getting an image container rendered. I thought it might have been the path to the image but even when I tried to map to a image from an existing site using the full qualified path nothing would render.
Edit: For clarification there are no asp.net controls in the main page (link or image) this for loop is iterating a collection and creating the controls at runtime. The last line entityHolder is a ASP.NET panel that the buttons are added to.
Can someone help me understand what I am doing wrong if this is even possible. I have to use a LinkButton and not an ImageButton as I need to render both text and image.
Cheers
You would have to do it manipulating the Text property of the control to also render the <img tag for example:
foreach (var entity in metadata.Meta.Where(e => e.ReportableObject == true))
{
LinkButton lb = new LinkButton();
string iconpath = ResolveClientUrl("~/images/search/" + entity.ClassName + ".png");
lb.CssClass = "entityIcon";
lb.Text = string.Format(#"image <img src=""{0}"" class=""{1}"" />",iconpath,"imgSize");
entityHolder.Controls.Add(lb);
}
Use the background css attribute instead of adding a new control.
LinkButton lb = new LinkButton;
string iconpath = "~/images/search/" + entity.ClassName + ".png";
lb.Style.Add("background", "url('" + base.ResolveUrl(iconpath) + "') left center no-repeat");
lb.CssClass = "entityIcon";
lb.Text = entity.ClassName;
entityHolder.Controls.Add(lb);

Dynamicly creating imageButton that calls a JavaScript function in c#

I have the following c# code that creates image buttons which should call the javaScript method below
var imageButton = new ImageButton();
imageButton.ImageUrl = "Styles/unClicked.png";
imageButton.ID = "btn" + questionName;
imageButton.OnClientClick = "buttonPressed('" + questionName + "')";
Its outputting & # 3 9; instead of the ' in the html code and there for is causing an error (Ive had to add spaces tp prevent SO changing it to a comma)
onclick="buttonPressed('question0')
how to I prevent this?
Please try this one HtmlString (not working).
imageButton.OnClientClick = new HtmlString("buttonPressed('" + questionName + "')");
If it will not work, than you will need to create custom control or use javascript (JQuery) to add handler for click event.
<script>
$("<%=imageButton.ID%>").click(function() {
buttonPressed('<%=questionName%>');
})
</script>
The OnClientClick attribute is very limiting. Not totally sure this will work, but I have use similar code before to handle ghost text in textboxes...
imageButton.Attributes.Add("onclick", "buttonPressed('" + val + "')");
The attribute should not be HTML encoded.

Trying to programatically add div with spans within to a div on an asp.net page. Getting errors/null references

I have a dynamic number of data elements that need to be added to my asp.net page. I am currently trying to do this by looping through a result data set like this:
protected void Page_Load(object sender, EventArgs e)
{
UserDB db = new UserDB();
string employeeIDOrName = Request.QueryString["employeeID"];
DataSet ds = db.GetUserSearch(employeeIDOrName);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
string employeeID = row[0].ToString();
string emailAddress = row[1].ToString();
string phone = row[2].ToString();
string details = emailAddress + " | " + phone;
UserControl uc = new Controls_EmployeeSearchResults(employeeID, details);
placeholder1.Controls.Add(uc);
}
}
Then in the employeeSearchResults code, I have:
<div class="returnDataBoxSup" onclick="insertAddedSup('1091912','Shawna Burns');">
<div id="searchResults" runat="server">
</div>
</div>
for the ascx page and
public Controls_EmployeeSearchResults(string name, string details)
{
/*<div class="returnDataBoxSup" style="overflow:hidden;" onclick="insertAddedSup('1091912','Shawna Burns');">
<span ID="spanName" runat="server" style="text-transform:capitalize; white-space:nowrap"></span><br />
<span ID="spanDetails" runat="server" style="font-size:0.7em; white-space:nowrap"></span>
</div>*/
//Div
HtmlGenericControl div1 = new HtmlGenericControl("div");
div1.ID = "returnDataBoxSup";
div1.Attributes["style"] = "overflow:hidden;";
div1.Attributes["onClick"] = "insertAddedSup('1091912','Shawna Burns');";
div1.Attributes["class"] = "returnDataBoxSup";
//Span Name
HtmlGenericControl span1 = new HtmlGenericControl("span");
span1.ID = "span_" + name;
span1.Attributes["style"] = "text-transform:capitalize; white-space:nowrap";
span1.InnerHtml = name;
//Span Details
HtmlGenericControl span2 = new HtmlGenericControl("span");
span2.ID = "spanD_" + name;
span2.Attributes["style"] = "font-size:0.7em; white-space:nowrap";
span2.InnerHtml = details;
div1.InnerHtml = span1.ToString();
div1.InnerHtml += span2.ToString(); ;
//div1.Controls.Add(span1);
//div1.Controls.Add(span2);
//searchResults = new HtmlGenericControl("div");
searchResults.InnerHtml = div1.ToString();
}
in the code behind. I first tried to add the span controls to the div, but I was receiving an exception. When I tried to add the controls to the inner html, it said that it could not convert the control type to string. Is there any way that I can do what I am trying to do?
I receive employee data in a data set, then I want to loop through those and create a stylized div for each employee record and display it on my page. Any thoughts?
Using the user control isn't a bad idea, using a ListView could be a lot better/easier though.
But lets say you stick with a div and a user control for now. Firstly, you don't create usercontrols the same way you create other controls because you are part way through the page life cycle and they need to be caught up. Instead use LoadControl (see: https://stackoverflow.com/a/4786121/328968).
Second, don't pass the values into the constructor. Create a function in your usercontrol called LoadData and pass the values to that. After creating your usercontrol using LoadControl you call LoadData and pass in the values. LoadData takes care of loading the data into the various controls which, unlike your example, should probably already exist in your usercontrol.
Try the InnerText to see if it works.

Categories

Resources