HTML Select items count in asp.net - c#

Hi I've an HTML select control in my ASP.NET page and I made it as runat = "server" and now I tried to add some list items to it dynamically. something like below code
var list = document.getElementById('<%=list1.ClientID%>');
var newListItem = document.createElement('OPTION');
newListItem.text = "Emp1";
newListItem.value = "e101";
list.add(newListItem);
<asp:Panel ID="pnlemp" runat="server"
Style="display: none;"
CssClass="modalPopup"
width="700px" Height="350px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<select id="list1" multiple="true" name="list1" runat="server">
</select>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
and now when I try to access this from my code like list1.Items.Count it is showing 0.
Anything wrong in this?
Thanks in advance

When you modify the html in a client side script, the viewstate (which keeps track of all the controls) doesn't update . That results in that when you make a postback the new items isn't "there" .
Sometimes there's a __doPostBack() javascript which forces a postback, but I'm not sure it'll work .

For solution to this problem either add items dynamically through server side code or
dont bring server side into the picture and handle everything via javascript.
Items added via javascript will not be persisted by asp.net. further more you may recieve a "Invalid Callback or PostBack Argument" Exception for the same because it will not understand from where these listitems(options) have been added in the Select.

Related

RadAjaxLoadingPanel does not works with DNN

I have a dnn site, which has a label and an imagebutton, clicking on which replaces the label with textbox and user can enter their text, once submitted the label will be updated with this text. Now clicking on the imagebutton causes the page to postback, i don't want a postback for this, hence i have placed telerik RadAjaxLoadingPanel control, so the cool loading div gets displayed while processing is going on, but for some reason it's not working, It always throws below error:
Please, see whether wrapping the code block, generating the exception, within RadCodeBlock resolves the error.
Below is the markup of my page: (I tried the wrapping the code with RadScriptBlock and RadCodeBlock, in both case it throws same error as above)
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<a class="subscribetoday" href="#">
<strong>Subscribe Today!</strong> <asp:Label ID="lblsubscribemsg" runat="server" Text="12 issues for $14.95"></asp:Label>
<asp:ImageButton ID="imgEditSubscribe" runat="server"
OnClick="imgEditSubscribe_Click" ToolTip='Edit' ImageUrl="~/images/edit.gif" AlternateText='Edit' Visible="false" />
<div id="editsubscribe" runat="server" visible="false">
<asp:TextBox ID="txtSubscribe" runat="server"></asp:TextBox> <asp:ImageButton ID="imgSave" runat="server"
OnClick="imgSave_Click" OnClientClick="return validateSubscribeNote();" ToolTip='Save' ImageUrl="~/images/save.gif" AlternateText='Save' /> <asp:ImageButton ID="imgCancel" runat="server"
OnClick="imgCancel_Click" ToolTip='Cancel' ImageUrl="~/images/cancel.gif" AlternateText='Cancel' />
</div>
<img src="img/prosound-subscribe.png" alt="Subscribe Today!">
</a>
</telerik:RadScriptBlock>
</telerik:RadAjaxPanel>
Can anyone tell me where i am going wrong with this.
The problem is with other server code blocks on the page (<%=%> for example, generally - <% ... %>), not with this concrete piece of code you are trying to AJAX-enable. You can read more here: http://docs.telerik.com/devtools/aspnet-ajax/controls/ajax/radcodeblock-and-radscriptblock
So, you should find the place where those code blocks are used and wrap THEM in a RadCodeBlock controls. It is often scripts that reference controls, e.g.:
<telerik:RadCodeBlock runat="server" ID="RadCodeBlock1">
<script>
function getReference() {
return $find("<%=someControl.ClientID%>");
}
</script>
</telerik:RadCodeBlock>
With DNN, however, I cannot say where these may originate.
Thus, your other option is to use an <asp:UpdatePanel> control to get AJAX requests instead of full postbacks. The native AJAX toolset also offers the <asp:UpdateProgress> control that you can use instead of RadAjaxPanel.

How to disable UpdateProgress for certain controls in ASP.NET?

I have a website developed by using ASP.NET. In there lot of ajax request are happening. So I want to display a image when ajax request is happening and hide the image after data loaded. Now this is works fine,
Here what I did so far
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="uppnlLocation">
<ProgressTemplate>
<img src="images/loading.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="uppnlLocation">
<ContentTemplate>
<asp:DropDownList ID="ddContinents" runat="server" CssClass="form-control" OnSelectedIndexChanged="ddContinents_SelectedIndexChanged" AutoPostBack="true"> </asp:DropDownList>
<asp:TreeView runat="server" ID="tvCountries" OnSelectedNodeChanged="tvCountries_SelectedNodeChanged"></asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
So in above code when a user select a continent from the dropdown list the countries which belongs that continent will be load to the below treeview. So I want to display a loading image when a user select a continent from the dropdown while loading the countries. Now this is working. But the problem is when user select a tree node in treeview It also shows this progress control image. I don't want to display that image on that action. How to disable it?
I saw a post regarding this.
Is there a way to disable UpdateProgress for certain async postbacks?
I implemented it. but then postback is not happening for the dropdown menu.
So how to achieve this?
Thank you very much.
Its better just to use the DisplayAfter parametre to raise the delay that this is appears because I understand that this just happening so fast. Do not go with complicate javascript solutions just add a delay of 1 or 2 seconds...
<asp:UpdateProgress ID="UpdateProgress1"
runat="server" AssociatedUpdatePanelID="uppnlLocation" DisplayAfter="2000">
<ProgressTemplate>
<img src="images/loading.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
Well why not just use javascript to force it display none if you are okay with it...
For normal update panel and to call update progress is not always show up. Better to use javascript to pop up update progress rather than using default ways.
Code to pop up Update Progress
function showUpdateProgress() {
var updateProgress = document.getElementById("<%=upProgress.ClientID%>");
updateProgress.style.display = 'block';
}
function HideUpdateProgress() {
var updateProgress = document.getElementById("<%=upProgress.ClientID%>");
updateProgress.style.display = 'none';
Sys.Application.remove_load(HideUpdateProgress);
}
If you are using this way when your job is done in Code behind u need to call javascript to hide the update progress
As per following
In CS file
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Script", "Sys.Application.add_load(HideUpdateProgress);", true);
Hope this help you

How to avoid AutoPostBack in a FormView?

I have an inherited ASPX page which has a FormView within a Form tag.
ie:
<body style="margin:0px;" bgcolor="skyblue">
<form id="form1" runat="server" action="Default.aspx">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="background-color: #87ceeb; vertical-align: top; text-align: center;">
<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" DataSourceID="SqlDataSource1"
OnItemInserting="FormView_Inserting" OnItemInserted="FormView_Inserted" BackColor="#00C0C0" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px">
<InsertItemTemplate>
etc
etc
As you can see I am using Ajax because further down the form there are CalendarExtender controls to handle dates.
The date textbox fields all have AutoPostBack="true" because the program would do nothing on the server side. ie: no events were firing. This was happening across all browsers - IE, FF and Chrome. Don't care about Safari, etc at this stage.
The point is I think I have fallen into "autopostback hell", where too many controls that do validation and other control manipulation have AutoPostBacks set to "true".
What is the better way to handle situations where controls such as textboxes, dropdownlists, etc need to perform actions before the form is SUBMITted? I would assume this is a common requirement in any form development project.
I saw somewhere (link) that wrapping FormView controls inside an UpdatePanel and ContentTemplate avoid the use of AutoPostBack. Can someone please explain some more on that?
Thank you
UPDATE
Setting my controls to AutoPostBack="true" is not a solution, because it upsets other areas of my DetailsView control and they do a postback as well. Again I suspect I have to wrap the formview inside something like an UpdatePanel to avoid autopostback entirely or do the data manipulation entirely in JScript, which I hate. But I may not have any choice.
It depends on what kind of validation you are doing. If you are doing simple validation (like required fields or regular expression validation) then you can just do the validation in javascript; no post back is required. There's even an <asp:RequiredFieldValidator> and <asp:RegularExpressionValidator> that you can use.
If you need to validate your data against the database, then you need to make a server call somehow. If you don't want to do a full page refresh, then you need to use AJAX. The easy way is to wrap each field that needs server-side validation in an <UpdatePanel>. For example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"
ChildrenAsTriggers="True" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" />
<asp:Label ID="Label1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Even though AutoPostBack is true, it will only update the contents of the <UpdatePanel>, so it won't disrupt your other content.
As a note, UpdatePanels will still post all of your form data with each partial post back. (The benefit it that the response only updates the contents of the UpdatePanel, not the entire page.) What this means is that if you have a large form with a lot of fields, you could be sending a lot more data than you want over the wire, because the AJAX post back will post the value of every field back to the server, when you really only need the value of one field. To avoid this, you can use page methods instead of update panels. However, they are a lot more work since you need to write a bunch of javascript.

Update Panel AsyncPostBack and PostBack triggers

I have a page in which much of the HTML is generated by client side script (JQuery). I added a server side ASP.NET File control to upload files to server.
Now files are getting uploaded on the button click, which causes POSTBACK and so all the textboxes Company Name, Street Name, City Client etc are lost, as they were generated by JQuery.
I put the upload portion in UpdatePanel and registered AsyncPostBack Trigger, but then I am not getting HttpContext object at code-behind. I turned Async to a full postback using PostBackTrigger then the things became the same as before(i.e. without an update panel).
Now I have two questions from you people:
- What is the use of an update panel if it behaves in the same way as the page without an update panel. (PostBackTrigger)
- What should I do with the above problem?
CODE:
<asp:UpdatePanel ID="uploadUpdatePanel" runat="server">
<ContentTemplate>
<input id="fileField" type="file" runat="server" multiple="multiple" />
<asp:Button ID="uploadButton" runat="server" Text="Upload Documents" OnClick="uploadButton_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="uploadButton" />
<%--<asp:PostBackTrigger ControlID="uploadButton" />--%>
</Triggers>
</asp:UpdatePanel>
Basically, FileUpload controls don't work in UpdatePanels. I've run into this issue before and as far as I know, there's no way around it. You're just going to have to accept a full PostBack and work on saving user inputs.
I would respectfully disagree with CrazyPaste's declaration that the UploadFile control doesn't work inside an update panel. I spent hours on this problem and finally found the answer on an obscure five-year-old post on the asp.net forums.
Check to see if your .aspx <form> tag looks like this:
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
If it is an unadorned tag like <form id="Form1" runat="server"> that's probably your problem.
The majority of responses I found elsewhere mentioned setting the update triggers, as you have, and is correct, but setting the triggers is useless if your form tag is not correctly configured. Nowhere except on the 2007 forum page was this suggestion made. It works great now.
I hope this helps!

Unable to get value Textbox by id in javascript

I have text boxes and it has values let say. I am calling my javascript method on one of textbox 'onblur'. my function is:
function CalculateExpectedProductPrice() {
alert("hi i called");
var originalPrice = document.getElementById('hdnSelectedProductPrice').value;
var numberOfLicenses = document.getElementById('txtNumberOfLicense').value;
var enteredAmount = document.getElementById('txtAmount').value;
alert(originalPrice);
alert(numberOfLicenses);
alert(enteredAmount);
}
i am getting alert message as ""hi i called". but not further.
But some i am not getting values of these controls.
*Edited:* My HTML is :
<asp:HiddenField ID="hdnSelectedProductPrice" runat="server" />
<asp:TextBox ID="txtAmount" runat="server" Width="250px"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtNumberOfLicense" runat="server" Width="35px" ></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtNumberOfLicense" EventName="" />
</Triggers>
</asp:UpdatePanel>
Will there any impact master-content page . because script is in content page and html also on same content page.Also let me know you, I am using wizard control where as all these controls are resides on second step of wizard. will that make any impact ?
Edited:
I think wizard control making here matter. As i started my firebug and review the generated html it assign the Id dynamically to those controls which are inside the wizard. thats why javascript unable to find the expected control .
eg for txtAmount text box which is inside the wizard control getting name as :
ctl00_ContentPlaceHolder1_Wizard1_txtAmount
but certainly i would not prefer to use this generated Id. So is there any remedy to find control inside the wizard control and get - set values ?
get id of the control as shown below
var enteredAmount = document.getElementById('<%=txtAmount.ClientId%>').value;
It's impossible to say for certain with your not having quoted your HTML (!), but the usual reason for this is confusion between the id and name attributes. document.getElementById works with the id attribute, but people tend to think it works with the name on input fields, which it doesn't (except for on IE, where getElementById is broken).
(The other thing to remember is that id values must be unique on the entire page, but looking at the IDs you quoted, I suspect you're okay on that front.)
Update: It works if you use ids:
HTML:
<form>
<input type='hidden' id='hdnSelectedProductPrice' value='10'>
<input type='text' id='txtNumberOfLicense' value='2'>
<input type='text' id='txtAmount' value='3'>
<br><input type='button' id='theButton' value='Click Me'>
</form>
Live copy
As T.J. mentioned we really need to see your html code, without seeing it it could be that you are looking for an elements attributes.
So lookup the element as you are already with
var element = document.getElementById('product');
Once you have the element you can query its attributes
var price = element.getAttribute('price');
If its "ASP.net server control" then you will have to do it like this:
var originalPrice = document.getElementById('<%=hdnSelectedProductPrice.ClientID %>').value;
if you use Asp.Net 4.0 and your textbox is unique on the entirepage you can add ClientIDMode="Static" in attribute of your textbox
<asp:TextBox ID="txtAmount" runat="server" Width="250px" ClientIDMode="Static"></asp:TextBox>

Categories

Resources