how to call a written function in .aspx page from code behind - javascript

i have an asp:DropDownList and i want to disable it in some condition.it can happen with a function in aspx page.but from code behind (after some c# work) it wont!
this is the element:

ASPX:
<asp:DropDownList ClientIDMode="Static" ID="cmbState" runat="server" Width="130px" Height="30px" Font-Size="Small" Font-Bold="true" DataValueField="StateID" DataTextField="Name" AutoPostBack="True"></asp:DropDownList>
Code-Behind:
bool condition = true;
if (condition == true)
{
cmbState.Enabled = false;
}
This should work unless you have something in your Page_Load method which would counter it.
The AutoPostBack property is important due to the order in which events are carried out on the page.

Related

Enable button after an item in ListBox is selected

At the moment I'm using
<asp:ListBox ID="UserListBox" runat="server" AutoPostBack="true" OnSelectedIndexChanged="UserListBox_SelectedIndexChanged"></asp:ListBox>
the button is disabled by default and after the OnSelectedIndexChanged is fired I am executing this behind.
protected void UserListBox_SelectedIndexChanged(object sender, EventArgs e)
{
loginBtn.Enabled = true;
}
This is causing the site to reload. I don't want that, instead I need javascript but I'm not familiar.
#Marco's answer is definitely more in-line with what you're looking for in the Web Forms world, but if you're set on using JavaScript start with:
document.getElementById("loginBtn").disabled = true;
This assumes that you've given your login button a fixed ID and ASP.NET isn't automatically assigning something crazy.
You'll have to remove the server-side event handler UserListBox_SelectedIndexChanged and replace it with a JavaScript event handler, otherwise the button will be disabled by JavaScript, but then the page will reload and undo the disable. If you had any other server-side code in that method it would need to find a new home, or you'd have to start really hacking at it.
Reasons like this are why it's nice to be able to stick with a single paradigm - do either server-side Web Forms work or client-side JavaScript. Avoid mixing & matching unless absolutely necessary - it's doable, but there will be tears and long nights.
Solution using javascript:
<script>
function checkSelect() {
if (document.getElementById('<%=UserListBox.ClientID %>').value != '')
document.getElementById('<%=loginBtn.ClientID %>').disabled = false;
}
</script>
just before </asp:content> also my list box now is:
<asp:ListBox ID="UserListBox" runat="server" onchange='checkSelect(this);'></asp:ListBox>
A usefull way to solve it is use update panels:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:ListBox ID="UserListBox" runat="server" AutoPostBack="true" OnSelectedIndexChanged="UserListBox_SelectedIndexChanged"></asp:ListBox>
</ContentTemplate></asp:UpdatePanel>
....
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:ListBox ID="loginBtn" runat="server" AutoPostBack="true" OnSelectedIndexChanged="UserListBox_SelectedIndexChanged"></asp:ListBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UserListBox" EventName="SelectedIndexChanged" />
</Triggers></asp:UpdatePanel>
Hi you can simply use jquery to achieve the same, please consider below example
<div>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Banana" Value="3"></asp:ListItem>
<asp:ListItem Text="Guava" Value="4"></asp:ListItem>
<asp:ListItem Text="Pineapple" Value="5"></asp:ListItem>
<asp:ListItem Text="Papaya" Value="6"></asp:ListItem>
<asp:ListItem Text="Grapes" Value="7"></asp:ListItem>
</asp:ListBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" Enabled="false"/>
</div>
and register change event of select list in $(document).ready event of jquery like shown below
<script type="text/javascript">
$(document).ready(function () {
$('select[id*=ListBox1]').change( function () {
if($('select[id*=ListBox1] :selected').length >0)
$('#<%= btnLogin.ClientID%>').prop('disabled', false);
else
$('#<%= btnLogin.ClientID%>').prop('disabled', true);
});
});
</script>
comment for any problem, Enjoy !!

ASP.Net get ScriptManager.RegisterClientScriptBlock return on UpdatePanel hiddenField

I am trying to obtain the return of a Javascript function that I call ont server side using ScriptManager.RegisterClientScriptBlock .
Currently, my javascript function save the value in a HiddenField that is contained in an UpdatePanel. When I call the method , I run the ScriptManager.RegisterClientScriptBlock and after that get the value of the HiddenField , but always returns me the value of the previous call. Here I show the code:
My User Control ASPX Side:
<script>
var num = 0;
function getReturn() {
num = num + 1;
var hr= document.getElementById('<%= hdf.ClientID %>');
hRetorno.value = num;
}
</script>
...
<asp:UpdatePanel ID="up1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:HiddenField ID="hdf" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
My User Control Server Side Code:
public String GetReturn()
{
return MyControl.jsGetReturn(this.Page, this.hdf);
}
private static String jsGetReturn(Page page, HiddenField hid)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "key", "getReturn();", true);
return hid.Value;
}
Index Page ASPX Side:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="width:720px; height:480px;">
<uc1:MyControl runat="server" id="MyControl1"/>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
<asp:TextBox ID="txt" runat="server" ></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
Index Page Server Side Code:
protected void btn_Click(object sender, EventArgs e)
{
txt.Text = MyControl1.GetReturn();
}
You can not do these things simultaneously.
Set value of hidden field from server side code using javascript via RegisterClientScriptBlock or RegisterStartupScript.
And retrieve that hidden filed value in server side code at the same time.
This is because, (changed) hidden field value is available to server-side code only when there is postback, when you set the value from server-side, there is no postback happening, that is why you are always getting previous value , i.e. that old value which is posted back to page.
EDIT
When you invoke RegisterClientScriptBlock or RegisterStartupScript, it won't make JS call instantly, rather it just append a javascript call before or after <form.. tag based on what you used and they are called on document load, so that means in jsGetReturn when you call RegisterStartupScript, it will set value of hidden field in document load, - hid.Value will not have updated value, as it is yet to be incremented via document load.

ASP.Net session not updated in javascript

when my button is clicked I fire the javascript to get the session..
But value of session not updated...
alert('<%= Session["file"]%>');
It won't be up to date if its changed after the page is rendered.
You might want to look at page methods (an ajax system) or another ajax approach.
Any inline code once rendered to the page will not change, which is a normal behavior.
use a Hidden field instead.
mark-up:
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Session["file"] = "Data Here";
HiddenField1.Value = Session["file"].ToString();
}
javascript:
alert(document.getElementById('<%= HiddenField1.ClientID %>').value);

AjaxControlToolkit:TabPanel

This control has a property Enabled that acts exactly as Visible behaves i.e. ?.Enabled = false hides the control.
I need to be able to keep all the tabs visible but some to be disabled under code control.
Any hints as to how I can achieve this? Thanks.
Try to set Enabled property for TabPanel.
<ajaxToolkit:TabContainer
ID="TabContainer1" runat="server" ActiveTabIndex="0">
<ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="TabPanel1"></ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2"></ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="TabPanel3" Enabled="False" runat="server" HeaderText="TabPanel3"></ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
Or in code-behind,
TabContainer1.Tabs[0].Enabled = false;
Here is one possible solution using client-side scripting. Basically, handle the OnClientActiveTabChanged event for the TabContainer (which fires whenever the active tab is changed). Then, if the tab is one that you don't want the user to use, change the ActiveTabIndex property of the TabContainer back to one that is acceptable.
Tab Container:
<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1"
Height="126px" Width="400px" ClientIDMode="Predictable"
onclientactivetabchanged="tabClickCheck" >
<asp:TabPanel ID="TabPanel1" runat="server" HeaderText="TabPanel1">
</asp:TabPanel>
<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2">
</asp:TabPanel>
<asp:TabPanel ID="TabPanel3" runat="server" HeaderText="TabPanel3">
</asp:TabPanel>
</asp:TabContainer>
Javascript handler:
<script type="text/javascript">
function tabClickCheck() {
var tabCont = document.getElementById("<%=TabContainer1.ClientID %>").control;
var tabInd = tabCont.get_activeTabIndex();
tabCont.set_activeTabIndex(2);
}
</script>
This function just sets the ActiveTabIndex to 2, regardless of which tab you clicked (you'll notice I'm also getting the current ActiveTabIndex, but I don't do anything with it - that's just to show you how). Obviously, use whatever logic makes sense for your app =)

Enable asp button only when there is text in the asp textbox

Ok, so I have a multiple ASP textboxes and ASP buttons on a page within a multiview.
The submit button associated with each textbox should be enabled only when there is text entered in the textbox. So, I wrote a Javascript function to handle this and I'm getting an error saying "document.getElementById(...)' is null or not an object"
function checkEmptyTxtBox(val, savebtn) {
if (val.value.replace(/^\s+|\s+$/g, "") == "")
document.getElementById(savebtn).disabled = true;
else
document.getElementById(savebtn).disabled = false;
}
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine"
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')">
</asp:TextBox>
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This is on VS2010.
You cannot set an attribute of a Server Side Control using <%= %>. If you look at the rendered source, it looks like this:
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')"
It literally contains the <%= %>.
You could set the attribute on page load like this:
protected void Page_Load(object sender, EventArgs e)
{
txt_Comments_2.Attributes["onkeyup"] = "checkEmptyTxtBox(this,'" + btnSave2.ClientID + "')";
}
EDIT:
As many will be willing to point out; this isn't really the "best" way to do event registration in HTML. Rather, the JavaScript should bind to the keyup event by adding an event listener. For example, with jQuery it becomes:
$(document).ready(function() {
$('#<%: txt_Comments_2.ClientID %>').keyup(function() {
if ($(this).val().replace( /^\s+|\s+$/g , "") == "") {
$('#<%: btnSave2.ClientID %>').attr('disabled', 'disabled');
}
else {
$('#<%: btnSave2.ClientID %>').removeAttr('disabled');
}
});
});
And your ASP.NET markup looks like this:
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine" />
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This has the advantage of not cluttering your HTML with event registration. There are even other, perhaps cleaner ways of doing this with something like KnockoutJS.
This might be because the ID of your button is btnSave2 but you're passing <%= btnSave2.ClientID %> as the savebtn. Javascript cannot find the element by the id which you specified.
Also, I just read up on people who have had a similar issue and theirs was that they did not do a RegisterStartupscript.
Please check these out:
http://forums.asp.net/t/1160208.aspx/2/10?document+getelementbyid+is+null+or+not+an+object
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Categories