asp:Label with nested control disappears on setting CssClass - asp.net

Is it improper to nest another control within asp:Label?
When I have another control (e.g., a button) inside my asp:Label, and I try to change CssClass on the label during an event handler, the entire label seems to disappear. I'll be grateful if someone can help me find what I might be doing wrong.
Bad1.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Bad1.aspx.cs" Inherits="Bad1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Badness?</title>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" Text="check and uncheck me" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged" />
<br />
<br />
<asp:Label ID="Label1" runat="server" > See me now? <asp:Button runat="server" /> </asp:Label>
</form>
</body>
</html>
Bad1.aspx.cs:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Bad1 : System.Web.UI.Page
{
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var lab = Page.FindControl("Label1") as Label;
lab.CssClass = "foo";
}
}
Symptom: Page displays correctly at first, and after first click on "check and uncheck me". But when I click on the checkbox a second time, the label ("See me now") disappears, never to come back. If I remove the button from within the label, there's no problem. So, is the nesting what's incorrect?

I would look into using a Panel instead of a Label.
<asp:Panel ID="Panel1" runat="server" CssClass="someStyle">
<asp:Button ID="Button1" runat="server" Text="Hi"></asp:Button>
</asp:Panel>
If you're looking to style the button, then you should apply your CssClass to the button directly. Use a Panel if you're trying to apply a style to that region/block.

Related

change text on button and enabled status after click button(asp.net)

I use ASP.NET to develop.
Here, I want the thing is that once I click button A (the text on the button A is "Start"), then the text on the button A will change to "processing...please wait" and button A will become not clickable. Then execute the stored procedure(the duration of stored procedure is 1 minute). After the stored procedure finishes, the text on the button A will change to "Start" and button A will become clickable.
I tried that before stored procedure, I added these codes:
ButtonA.Text = "processing...please wait";
ButtonA.Enabled = false;
And after stored procedure, I added these codes:
ButtonA.Text = "Start";
ButtonA.Enabled = true;
But the outcome is the text on the button A is not changed and button A is still clickable during the stored procedure is executing.
Can anyone tell me how to achieve what I want? Thanks.
Then I edit my aspx file to be below:
<asp:ScriptManager ID="MainScriptManager" runat="server"/>
<asp:UpdatePanel ID="pnlHelloWorld" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Button ID="ButtonA" runat="server" OnClick="ButtonA_Click" Text="Start" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ButtonA" EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
But the text of button still remains the same and the button is still clickable.
You can achieve your requirement by using Ajax. Using Ajax you can do partial page refresh.
Put ButtonA inside the UpdatePanel, and it should work as expected.
You can refer below sample code for reference.
webpage.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello, world!</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="pnlHelloWorld" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="ButtonA" OnClick="btnHelloWorld_Click" Text="Update label!" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
c# code
protected void btnHelloWorld_Click(object sender, EventArgs e)
{
//Before Procedure call
ButtonA.Text = "processing...please wait";
ButtonA.Enabled = false;
//Call Procedure
procedure ....
//After Prodedure call
ButtonA.Text = "Start";
ButtonA.Enabled = true;
}
Hope that helps, thanks.

Button OnClick event not firing with one textbox in the form

I came across a very strange occurrence with ASP.NET onclick event in IE (other browsers doesn't seem to have this problem). When there is only one textbox field in a form, the onclick event doesn't fire when you enter text and hit Enter/Return. The event does fire when you click on the actual submit button. When there are two or more fields in the form, hitting Enter/Return works just fine.
It's very strange. Thought it was something with my IE, but checked other machines, and every one of them had the same problem.
I had setup this really simple page as a test:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write(((Button)sender).Text);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBox2" runat="server" ></asp:TextBox>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
When one of the textbox is removed, the btnSubmit_Click event doesn't behave as expected.
The defaultButton property of Panel or Form is used to ensure Enter Key Submission. Typically people used to Enter Key submission and if it is disabled, it might be annoying certain times.
The defaultButton really provides a way to handle Enter Keys for respective portions of the page when the focus is there.
Source: multiple submit buttons and the enter key

asp.net dropdownlist - C#.NET and javascript

I have a drop down and a div right next to it. The text contained inside the div should be updated based on value selected in the dropdown.
I do NOT want to use AutoPostBack feature.
Use OnChange client side event of the dropdownlist control. Here is a sample that updates a div's inner text with the selected value of the dropdown list :
<asp:DropDownList runat="server" ID="myDDL"
OnChange="document.getElementById('myDiv').innerText=this.value;">
</asp:DropDownList>
<div id="myDiv"></div>
As people have said, you cannot access the C# codebehind code without performing a postback.
One way of accomplishing what you want is to use PageMethods. This is the Microsoft idiom for accomplishing this but there are lots of other Ajax libraries that will do it.
Provide a static method in your codebehind which will get called form your dropdownlist OnChange event.
[WebMethod]
public static string MyMethod()
{
// Your code goes here
return "The text for the div"
}
You then call this PageMethod from your .aspx page:
You need to add a scriptmanager (after the form tag)
<asp:ScriptManager ID="scriptmanager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" ></asp:ScriptManager>
Then in the OnChange event (or a function called from it) you have:
<asp:DropDownList id="ddl" runat="server" OnChange="PageMethods.MyMethod(OnComplete);" />
Where OnComplete is a javascript function that handlers the PageMethod response:
<script language="javascript">
function OnComplete(result, userContext, methodName) {
document.getElementById(yourDivId').innerText=result;
}
</script>
You can also have a paramaterised webmethod if needed:
[WebMethod]
public static string MyMethod(string myNeatParam)
{
// Your code goes here
return "The text for the div"
}
And call it with:
PageMethods.MyMethod('SomeValue', OnComplete)
Updated based on comments:
Here's a sample page on using an UpdatePanel to do what you need to do. Please keep in mind though that there is a full postback happening, even though it is transparent to the user.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdatePanelMadness._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ColorsDropDownList" runat="server" AutoPostBack="true"
onselectedindexchanged="ColorsDropDownList_SelectedIndexChanged">
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Blue" Value="Blue" />
</asp:DropDownList>
<div id="ColorDiv" runat="server">
<p>
Hello World!
</p>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
code behind:
namespace UpdatePanelMadness
{
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ColorsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
ColorDiv.InnerText = this.ColorsDropDownList.SelectedValue;
}
}
}

ModalPopupExtender and validation problems

The problem I am facing is that when there is validation on a page and I am trying to display a model pop-up, the pop-up is not getting displayed. And by using fire-bug I have noticed that an error is being thrown.
The button that is used to display the pop-up has cause validation set to false so I am stuck as to what is causing the error.
I have created a sample page to isolate the problem that I am having, any help would be greatly appreciated.
The Error
function () {Array.remove(Page_ValidationSummaries, document.getElementById("ValidationSummary1"));}(function () {var fn = function () {AjaxControlToolkit.ModalPopupBehavior.invokeViaServer("mpeSelectClient", true);Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);}) is not a function
http://localhost:1131/WebForm1.aspx
Line 136
ASP
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CLIck10.WebForm1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:Button ID="btnPush" runat="server" Text="Push" CausesValidation="false" onclick="btnPush_Click" />
<asp:TextBox ID="txtVal" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtVal" ErrorMessage="RequiredFieldValidator" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<input id="popupDummy" runat="server" style="display:none" />
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</div>
</form>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CLIck10
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOK_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnPush_Click(object sender, EventArgs e)
{
mpeSelectClient.Show();
}
}
}
This is an issue with using both ValidationSummary and ModalPopup.
see here: http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=12835
The problem is that there is a missing ";" between the two injected scripts.
Their solution is to create/use a custom server control that inherits from ValidationSummary, that injects a ";" into the page startup script to fix the bug:
[ToolboxData("")]
public class AjaxValidationSummary : ValidationSummary
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), this.ClientID, ";", true);
}
}
Try setting your ValidationSummary "Enabled" property to false on this event : "btnPush_Click"
; and then setting it back to enabled = "true" on this events : "btnOK_Click" ,"btnCancel_Click".
I think this will work if you do not have the validation summary inside the Panel that you want to pop up.But it is not a solution if you need the validation summary inside the pop up panel,...witch is my case :(.
Best Regards.
I tried all the available answer online but didn't worked any. Then i tried to move my modal popup extender at very end of the HTML and it works fine for me. Me and my users are Happy :)
I am not using FROM tag I am using Content place holder just like below:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<table id="tblMessage" runat="server" width="100%" >
<tr align="center">
<td align="center">
main content and
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
If you notice i have validation summary inside the panel because i want error message inside the pop up(i have some additional control in pop up too). and
Some more HTML tag here as i have so many other things to do in one page. right before closing tag of TABLE
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</table>
Done.it's working. Hope that works for other too.
Are you using validation groups anywhere on the page? I've had problems with control events not firing when they are not part of a validation group and other controls on the page are part of a validation group.
I'd try changing this:
<input id="popupDummy" runat="server" style="display:none" />
to something like this:
<asp:Button id="popupDummy" runat="server" CausesValidation="false" Visible="false" />
I bet the untyped input is requiring validation.
i had the same issue, adding ValidationGroup to the validation controls did the trick!
One other thing to try, if you don't need Client Script you can disable it in the markup. Doing that fixed our problem.
EnableClientScript="false"

How to assign a method's output to a textbox value without code behind

How do I assign a method's output to a textbox value without code behind?
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Public TextFromString As String = "test text test text"
Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")
Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
Return New String(Input, Count)
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=TextFromString%>
<br />
<asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
<br />
<%=TextFromMethod%>
<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>
</div>
</form>
</body>
</html>
it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.
It's also confusing to me why
<asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>
and
<asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>
works but
<asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>
causes a compilation error.
There's a couple of different expression types in .ASPX files. There's:
<%= TextFromMethod %>
which simply reserves a literal control, and outputs the text at render time.
and then there's:
<%# TextFromMethod %>
which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like:
<%$ ConnectionStrings:Database %>
but that's not really important here....
So, the <%= %> method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want.
The <%# %> method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work.
So - what to do? Just call TextBox.DataBind() at some point. Or, if you have more than 1 control, just call Page.DataBind() in your Page_Load.
Private Function Page_Load(sender as Object, e as EventArgs)
If Not IsPostback Then
Me.DataBind()
End If
End Function
Have you tried using an HTML control instead of the server control? Does it also cause a compilation error?
<input type="text" id="TextBox4" runat="server" value="<%=TextFromString%>" />

Resources