I have a page that contains a textbox and button, when the user clicks the submit button I want to display a message based on a bool value.
I have researched on stackoverflow and tried the code in this questions: Asp.net Webform Display Alert and redirect
But it didn't work. I have the following code:
ClientScript.RegisterStartupScript(this.GetType(),"", "alert('message')", true);
What code do I need to display the alert message?
you can use this simple method:
private void MessageBox(string msg)
{
Label lbl = new Label();
lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
Use this apporch
Response.Write(#"<script language='javascript'>alert('The following errors have occurred: \n" + strErrorDesc + " .');</script>");
Related
I'm doing a C# 3-tier project about pets
On load of the first webform I make a query to the database and get the data of all pets (id, name, photo) as a List to be shown as cards with images in HTML, I'm using Materialize by the way, I leave this link as example http://materializecss.com/cards.html
My code behind (Pets.aspx.cs) is this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
NegPet negPet = new NegPet();
StringBuilder sbHtml = new StringBuilder();
List<EntPet> listEntPet = negPet.getAllPet(5); //5 is the user code (get all pets from user 5)
if (listEntPet.Count > 0)
{
foreach (EntPet entPet in listEntPet)
{
sbHtml.Append("<div class=\"col s6 m4\">");
sbHtml.Append("<div class=\"card\">");
sbHtml.Append("<div class=\"card-image\">");
sbHtml.Append("<img src=\"http://www.dogzone.com/images/breeds/beagle.jpg\" alt=\"\" class=\"circle responsive-img\" />");
sbHtml.Append("<asp:LinkButton id=\"lb_"+ entPet.Id_pet + "\" runat=\"server\" CommandArgument='<%# Eval(\""+ entPet.Id_pet + "\") %>')");
sbHtml.Append("\" click=\"updatePet_Click\" class=\"btn-floating halfway-fab waves-effect waves-light red\"><i class=\"material-icons\">edit</i></a>");
sbHtml.Append("</div>");
sbHtml.Append("<div class=\"card-content\">");
sbHtml.Append("<span class=\"card-title\">");
sbHtml.Append(entPet.Name_pet);
sbHtml.Append("</span>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
}
} else
{
sbHtml.Append("<h2>No pets found</h2>");
}
galPet.Controls.Add(new Literal { Text = sbHtml.ToString() });
}
}
Where galPet is a
<asp:PlaceHolder ID="galPet" runat="server" />
This code returns me all the "Id" and "Name" of "Pets" and sets it in the HTML design that I want, similar to a gallery. The problem comes when I try to get to the event onClick="updatePet_Click" apparently it never reaches it's method behind
public void updatePet_Click(Object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument.Substring(3);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + yourValue + "');", true);
}
What I'm trying to do with this code is retrieve the ID from the clicked asp:LinkButton so I can use it in code behind
I also tried changing the event to "OnClick" but I got this error when tried to click it
Pets.aspx:24 Uncaught ReferenceError: updatePet_Click is not defined
at HTMLUnknownElement.onclick (Pet.aspx:24)
I would like to know how to retrieve the ID to work it in the code behind or if there is another way to pass my list to the HTML design where I can get the clicked ID easier. Thanks
I'm having some trouble with radio button validation in a wpf application, the radiobutton.checked function it throws an error. the 2 radio buttons are name TSBtn and DSBtn. the error that I get when I try and build the application is'
Error 2 The event 'System.Windows.Controls.Primitives.ToggleButton.Checked' can only appear on the left hand side of += or -= 115 23 MainServerWIndow
im not sure why this is happening the code I have Writen is bellow'
private void Bill_Click(object sender, RoutedEventArgs e)
{
if (TSBtn.Checked)
{
StringBuilder itm = new StringBuilder();
foreach (object selectedItem in yourOrder.Items)
{
itm.AppendLine(selectedItem.ToString());
}
MessageBox.Show("The server is " + serversname.SelectedItem + "\n" + "The table number is " + int.Parse(TableNumber.Text) + "\n" + itm);
}
else if (DSBtn.Checked)
{
yourOrder.Items.Add("The driver is " + DriverName.SelectedItem);
yourOrder.Items.Add("Delivery Address " + DeliveryAddress.Text);
}
}
does anyone have any ideas as to why this is happening?
thanks.
Your answer lies in the error message.
The event 'System.Windows.Controls.Primitives.ToggleButton.Checked' ...
Checked is an event, not a property.
What you want is the IsChecked property.
Checked is an Event. You should be testing the checked property which is IsChecked.
So your code should read:
if (TSBtn.IsChecked)
...
and
else if (DSBtn.IsChecked)
...
I've found this question solved at:
stackoverflow.com
if (radLot.IsChecked == true)
{
SymbolSpecification = "LotRenderer";
}
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();
At a certain point i have a dynamicly generated string with html in my code-behind.
I want to open a popup with has that html as its source.
I have tried the following:
I created this method on my .aspx site (Javascript):
function OpenWindowWithHtml(html, title) {
var myWindow = window.open('', title);
myWindow.document.write(html);
myWindow.focus();
}
And in the code-behind i have this:
Response.Write("OpenPopupWithHtml(\"" + html + "\", \"" + title + "\");");
But when i try to execute this i get an error.
Does anybody see, what i do wrong here?
Or does somebody know a better way to do this?
EDIT
on button click it shoudl be like this
protected void btnAbct_Click(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "OpenPopupWithHtml('" + html + "', '" + title + "');");
}
To execute the code ie. function you written in javascript
ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", "OpenPopupWithHtml('" + html + "', '" + title + "');");
you can register client script like this
if (!ClientScript.IsClientScriptBlockRegistered("exampleScript"))
ClientScript.RegisterStartupScript(this.GetType(), "exampleScript","
<script language = "'javascript'">
alert('you just registered the start up script')
</script>
");
from the code behind file of asp.net
To Open pop-Up window , just replace this line in above code
ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>window.open('{0}');</script>",
"mypage.html"));
Check this for detail : Register Client script in ASP.NET
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.