asp.net dropdownlist - C#.NET and javascript - asp.net

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

Related

asp:Label with nested control disappears on setting CssClass

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.

Updating ASP.NET label after button click, using UpdatePanel

I'm trying to have two things happen when I click on a button in an ASP.NET page:
Change the text in an ASP:Label.
Disable the button.
I've done a lot of research on this, but I've had difficulties doing either.
For #1, I thought that this should work, but it doesn't:
<%# 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">
Protected Sub BtnSubmit_Click(sender As Object, e As System.EventArgs)
Label1.Text = "Working..."
System.Threading.Thread.Sleep(5000)
Label1.Text = "Done."
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" />
<div>
<asp:ListBox runat="server" Height="100px" />
<br />
<asp:UpdatePanel runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnSubmit" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Press the button" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button runat="server" ID="BtnSubmit" OnClick="BtnSubmit_Click" Text="Submit Me!" />
</div>
</form>
</body>
</html>
The "Working..." message is never displayed.
As for #2, I added this to the button (I forget where I found it):
OnClientClick="this.disabled = true; this.value = 'Working...';"
UseSubmitBehavior="false"
That had the desired effect of disabling the button and changing its text (value), but it wasn't possible to change it back using Text and Enabled properties.
I just found a solution on msdn (http://msdn.microsoft.com/en-us/library/bb386518.aspx). Added some code and remove some unnecessary parts.
<%# 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 btnDoWork_Click(object sender, EventArgs e)
{
/// do something long lasting
System.Threading.Thread.Sleep(3000);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script language="javascript" type="text/javascript">
<!--
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
var postBackElement;
function InitializeRequest(sender, args) {
if (prm.get_isInAsyncPostBack()) {
args.set_cancel(true);
}
postBackElement = args.get_postBackElement();
if (postBackElement.id == 'btnDoWork') {
$get('btnDoWork').value = 'Working ...';
$get('btnDoWork').disabled = true;
}
}
function EndRequest(sender, args) {
if (postBackElement.id == 'btnDoWork') {
$get('btnDoWork').value = 'Done!';
$get('btnDoWork').disabled = false;
}
}
// -->
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Hello World!"></asp:Label><br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnDoWork" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnDoWork" runat="server" Text="Start!" OnClick="btnDoWork_Click" />
</div>
</form>
</body>
</html>
What you basically do, is you register some eventHandler for Initialize_ and End_Request - in those you disable and enable your button!
HTH
ASP will not flush the result to the browser while working even if you use an UpdatePanel. It will finish the jobb (including the sleep) before flushing.
You can use a UpdateProgress to show the "Working.." text.
<asp:UpdateProgress>
This will show its content while the UpdatePanel is working. Once the UpdatePanel is finished, the content will disappear.
What you need in you ClickEvent is:
Label1.Text = "Done."
btnSubmit.Enabled = false
This will show the Done text and disable the button. And tell the UpdateProgress to disappear.
The Working message is never displayed because you are executing the script on the server, which doesn't respond to the client until the method exits.
ASP.NET AJAX has a built in control for displaying messages like this while the UpdatePanel is waiting on the server.
Check out the UpdateProgress Control:
<asp:UpdateProgress runat="server" id="progress" ><ProgressTemplate>Working...</ProgressTemplate></asp:UpdateProgress>
You can disable the button by setting the Enabled property to false in your server-side method.
BtnSubmit.Enabled = false
#1: You will never see the message "Working" as you stopped the thread .... Every Message will be shown when your process has "ended".
#2: you coded clientSide to disable the button, there is no code to re-enable your button
hth
First off, "working" never appears because the final value of the label at the time of post-back is "Done." Think about what is happening here - you click the button which causes a post-back to the server. It processes the post-back which includes running the button click code, the result of which is then sent back to the browser. Your 'working' text never makes it back over the wire.
I am not clear on what you're trying to accomplish with the client-side code, but to do what you describe you're almsot there server-side:
Protected Sub BtnSubmit_Click(sender As Object, e As System.EventArgs)
Label1.Text = "Done."
btnSubmit.Enabled = false
End Sub
Also, but your button inside your update panel template tags so it participates in the ajax-postback.

how to change the inner html of a div

i have a div and an html editor and trying to:
add the div inner html to the
editor. (thats done)
then any changes done in the editor
is saved back in the div.
here is the backcode :
protected void Page_Load(object sender, EventArgs e)
{
Editor.Content = cvDiv.InnerHtml;
}
protected void preview(object sender, EventArgs e) //this is an onclick event
{
cvDiv.InnerHtml = Editor.Content;
}
and the code for the editor:
<asp:ScriptManager runat="server" />
<cc1:Editor ID="Editor" runat="server" OnContentChanged="preview" />
<asp:Button runat="server" ID="eButton" CssClass="eButton" Text="Edit" OnClick="Edit" />// this is the button that is supposed to save
but it doesnt work.
so what i am trying to do is save whatever changes made in the editor to the div
using asp.net 3.5, and the ajax toolkit editor.
thanks in advance.
This is an example i've made to show you a working code.
ASPX
<%# 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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:TextBox id="editor" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Save" runat="server" OnClick="SaveChange" Text="Save" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div id="preview" runat="server"></div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="editor" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) editor.Text = preview.InnerHtml;
else preview.InnerHtml = editor.Text;
}
protected void SaveChange(object sender, EventArgs e)
{
string thingsToSave = preview.InnerHtml;
//Save to db/file/xml
}
}
Can you try using Literal control rather than a server side <div /> ?

Cant seem to hide TableRow on AJAX postback

I wolud like to hide/unhide a TableRow through ASP.NET AJAX when a checkbox is clicked.
I have this code for the checkbox:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:CheckBox runat="server" ID="cbViewPages" Checked="true" OnCheckedChanged="OnViewPages" AutoPostBack="true"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbViewPages" EventName="CheckedChanged"/>
</Triggers>
</asp:UpdatePanel>
and this for the TableRow
<asp:TableRow runat="server" ID="PagesRow">
<asp:TableCell VerticalAlign="Middle">Test Row</asp:TableCell>
</asp:TableRow>
This method is called when the checkbox is clicked:
protected void OnViewPages(object sender, EventArgs e)
{
if(cbViewPages.Checked)
{
PagesRow.Visible = true;
}
else
{
PagesRow.Visible = false;
}
}
OnViewPages is definitely called, I can see that through the debugger.
And if I remove the AJAX code, OnViewPages is hidden/unhidden as required.
Why doesn't this hide/unhide functionality work with the AJAX code?
Doh!
I have a partial answer, the TableRow is not in the Update panel.
But you cant put an UpdatePanel around a TableRow.
So that's my new question, how do you put an UpdatePanel around a TableRow?
A couple of options. You could put the update panel around the entire table (this is what Petras is suggesting). You could also use JavaScript to do this. In the event that fires when your checkbox is checked/unchecked, just call
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "setRowVisibility", "setRowVisibility(" & IIf(cbViewPages.Checked, "true", "false") & ");", True)
This will call a JavaScript function you can define on your page like this:
function setRowVisiblity(visible) {
var row = document.getElementById('<%=PagesRow.ClientID %>');
if (visible) {
row.style.display = 'table-row';
} else {
row.style.display = 'none';
}
}
This is MUCH more efficient than using and Update Panel, but it's a little more work. I prefer efficiency, but that's just me. :)
Here's the solution:
ASPX page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!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="scriptMgr" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:CheckBox runat="server" ID="cbViewPages" Checked="true" OnCheckedChanged="OnViewPages" AutoPostBack="true"/>
<asp:Table runat="server">
<asp:TableRow>
<asp:TableCell>123</asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="PagesRow">
<asp:TableCell>Row To Hide</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbViewPages" EventName="CheckedChanged"/>
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Code behind page:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void OnViewPages(object sender, EventArgs e)
{
if(cbViewPages.Checked)
{
PagesRow.Visible = true;
}
else
{
PagesRow.Visible = false;
}
}
}

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"

Resources