post back occurs javascript listbox items lost in asp.net - c#

i have 10 list boxes in my aspx page for all 10 list boxes same function is using for some buttons i want to add listbox data to grid can you help me my java script code shown below
function MoveItem(ctrlSource, ctrlTarget) {
var Source = document.getElementById(ctrlSource);
var Target = document.getElementById(ctrlTarget);
if ((Source != null) && (Target != null)) {
while ( Source.options.selectedIndex >= 0 ) {
var newOption = new Option(); // Create a new instance of ListItem
newOption.text = Source.options[Source.options.selectedIndex].text;
newOption.value = Source.options[Source.options.selectedIndex].value;
Target.options[Target.length] = newOption; //Append the item in Target
Source.remove(Source.options.selectedIndex); //Remove the item from Source
}
}
}
i tried a javascript above code to move items between listbox using html input button problem when i trying to save listbox.items.count giving 0 can anyone tell me why this happening and also when post back occurs listbox items lost.

Dear,
This is a normal, any thing changed client side to the list box will not be reflected on the server side.
you can add an onclientclick event on the button and read the items from the listbox client side and save them using AJAX, or you can read the items from the listbox client side and put them in a hidden field as a string and you can read the value of the hidden field server side.
you can read all the item from the client side, and format them in your own format as a string.
then add an asp hidden field on the page, and client side put the string that you have in the hidden field value property.
now you can access the string from the onclick event on the server side and extract the items of the list boxes.

Related

Why label text is getting changed after clicking on asp.net button?

I have a WebForm ASP label and button. I am setting the label's value on page load. For example, the label text on page load is 2 items selected. This comes from the database. Then if the user changes the selection then it counts the selected values by jQuery and sets the text as 5 items selected.
When I click on the submit button to save changes, again it resets to 2 items selected. I didn't use an update panel. I don't know what is going on here. Can anyone please explain this scenario?
$("#lblCount").text($('#grdProducts').find('input#chkSelect:checked').length + ' Complementary Products added');
C# on page load:
lblCount.Text = ComplementaryproductCount.ToString() + " Complementary Products added";
I do not understand why the label text is changed on button click. I couldn't find anything while debugging too.
Thanks
When you set lblCount.Text in your code, that value is set into the ViewState of the page... that means when your page is posted back to the server (to handle an event, etc) ASP.Net knows what lblCount.Text was originally and can re-render the HTML with the same value.
As part of that post-back to the server, the browser will send back that ViewState along with any input control values (things like textboxes, dropdowns, hidden field).
What it does NOT do is post-back any changes you might have made to the elements on the page via things like jQuery (other than input controls I mentioned above).
The result is that although you've changed the element on the screen, the server knows absolutely nothing about that change, and it will re-send the original HTML for the label back to the browser.
Your only option is to do something as suggested by #John in his comment... you need to store the fact the element has changed in an input, and then use that.
For instance...
<asp:Label runat="server" id="lblCount" />
<asp:HiddenField runat="server" id="hdnCount" />
function updateCount(newCount) {
$("#<%=lblCount.ClientID%>").text("Count: " + newCount.toString());
$("#<%=hdnCount.ClientID%>").val(newCount.toString());
}
Then in your code-behind you can have...
if (!Page.IsPostBack)
{
var count = 1;
lblCount.Text = String.Format("Count: {0}", count);
hdnCount.Value = count.ToString();
}
else
{
lblCount.Text = String.Format("Count: {0}", hdnCount.Value);
}

Asp.Net data attributes dynamically updated through JS/jQuery but the updated attributes aren't updated when retrieved through code behind

I have an aspx page of images that, when selected, a popup appears prompting for various information tid bits that I then store the information as data attributes on hidden labels through use of jQuery (i.e. data-id="####", data-difficulty="###", etc.). I acknowledge that this isn't the best way to do it necessarily but I've tried other things (see below) and nothing has worked yet.
I've been attempting, and to no avail, to retrieve the dynamically updated data attributes so the various items can be stored to my local ms sql database. The updating of the attributes works perfectly in that I can view the items being updated properly in Chrome's developer tools. Despite this when I try to pull the same attributes I can see as being updated I'm unable to retrieve the updated values in the code behind and keep getting back the initial values (generally an empty string "").
Here's the implementation on the aspx page:
<asp:Label runat="server" ID="lblSelection" data-id="" data-count="" data-price="" data-difficulty="" CssClass="selected-items" />
and here's the relevant method being called when the "Submit" button is clicked further down on the same page:
protected void SubmitClicked(object sender, EventArgs e)
{
var currentID = lblSelection.Attributes["data-id"];
var currentCount = lblSelection.Attributes["data-count"];
var currentPrice = lblSelection.Attributes["data-price"];
var currentDifficulty = lblSelection.Attributes["data-difficulty"];
if (currentID == null || currentID == "")
{
// stop and throw an informative message to the user
}else{
// keep processing ...
}
}
The trouble is that when I run the project in debug mode and inspect those elements (again, making sure that I can visually see that the attributes are actually updated in the developer tools) they're all the initial value of "". My only guess is that there's some kind of post back issue but I wouldn't think that would happen until my method had been called and fully processed. As a note, I'm populating the images onto the page and updating their attributes already through a sql call based on the id of the item:
<img runat="server" src="" data-id="12345" />
The initial loading all works perfectly so I can clearly set the properties from the code behind fine. For whatever reason though I am unable to pick up the updated attribute values in the code behind after the jQuery updates the label's attributes (following some clicking and whatnot). Any tips or thoughts on this would be greatly appreciated.
What you are trying to do cannot work because:
The value of custom attributes is not posted back to the server (as discussed here).
Even if you set the text of the Label in client code, it would also not be available in the Text property in code-behind. A Label is rendered as a span element in the page, and the content of that type of element is not posted back to the server.
A nice list of properties included in a postback is given in this topic: Which values browser collects as a postback data?
As suggested by mshsayem, you should use HiddenFields. If, for some reason, you want to do it differently, you could use hidden TextBoxes, set their value in client code, and retrieve it with the Text property in code-behind. In other words: HiddenFields are not the only controls for which a value set in client-code can be retrieved in code-behind (but they are the obvious choice if the control is not to be displayed).

How can I grab a textfield value in Ext.Net?

I know there's a lot of information on this, but mine doesn't seem to be working out so well. I have a form that's created in C# in a form panel. My textfields are created like below:
Ext.Net.Panel panel = new Ext.Net.Panel();
Field field = null;
field = new TextField();
field.Name = "FieldTitle";
field.ID = "FieldID";
panel.Add(field);
this.searchform.Add(panel);
this.searchform.Add(new Ext.Net.Button()
{
Text = "Search",
Handler = "getID();"
});
When the search button is hit, then a JavaScript function is called which performs a store reload:
Ext.getCmp("#Gridpanel").getStore().reload({});
On the reload, I want to read the form fields and use the text for another part of the code. However, the below code doesn't seem to be working:
if(X.isAjaxRequest){
var ctrl = X.GetCmp<TextField>("FieldID");
string value = ctrl.Value.ToString();
}
I can get inside the 'if' statement, but ctrl comes back as null. Is there something else I need to include to grab the text field data?
EDIT
So I'm realizing that I'll have to pass an array of the search field ID's to a JavaScript function, then send a dataset back to the server side in order to implement the search. Just to throw it out there, is there a way to dynamically create controls (ie; a TextField) in C# and then get the value from those controls after an event is fired (ie; a button click)?
You can try to get the textfield using
Ext.getCmp("#FieldID") or X.getCmp("#FieldID"). FieldID is the client ID for TextField.
Use developer Tools to check the ID for the TextField

Changing input value using javascript

I've been looking for a reason why this doesn't work, but I can't find one. In my asp.net application I create a a bunch of hidden inputs in c# and then try to modify them in javascript before I call them back to the server.
My c# code:
hidden3 = new HtmlInputHidden();
hidden3.ID = "total";
hidden3.Value = index.ToString();
this.Controls.Add(hidden3);
my javascript code:
mod = document.getElementById("total");
mod.value = newVal;
I can call the value back fine but it doesn't change. I have also added alerts for the original value and then the value after changing values and they both show up fine. However the code is never changed so when I pull the values
To get the value back I am using this;
HtmlInputHidden hiddenControl = (HtmlInputHidden)FindControl("total");
Have you verified that the resulting input tag as the ID of "total"? By default, in Webforms, the actual client-side ID is prefixed with the parent's Id (and a delimiting character); this helps to ensure that IDs are unique. One way to get the real client-side Id is to pull the value from the ClientID property of the control, but you should only look at that value once it has been put in a Controls collection.
These controls are dynamically created and they have to be created in each postback. However, these should be built before Page_Load preferably in Page_Init event handler. If these are created in Page_Load, the view state has already been processed and the control can't be set from the posted value.

Maintain value in Fileupload control in asp.net,C#

i am using Fileupload and 3 dropdown control in update panel, 3 dropdown will be post back on dropdown selected index change event (i.e like Country,states and city... get the value from db as per country,states and city)
THE PROBLEM IS
While postback the filename path is gone from the file upload control(as expected/ or Default property).
I am converting the file to byte array, to store in the database from file upload control.
How can i retain the value or Is there any way to solve this issue.
Is there any ajax control for file upload or any free controls which retain the value after postback also...?
Or it is possible to set the value to file upload control during postback ?
Thnks in Advance
You can try to persist file upload value in hidden field between async post-backs using asp.net ajax event handlers.
Sys.WebForms.PageRequestManager.instance.add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.instance.add_endRequest(EndRequestHandler)
function BeginRequestHandler(sender, args) {
var fileUpload = document.getElementById('fileUpload');
var hiddenUpload = document.getElementById('hiddenUpload');
hiddenUpload.value = fileUpload.value;
}
function EndRequestHandler(sender, args) {
var fileUpload = document.getElementById('fileUpload');
var hiddenUpload = document.getElementById('hiddenUpload');
fileUpload.value = hiddenUpload.value;
}
On post back you could hide the FileUpload control and show a Literal that displays the value of the file.
Then, if the user wants to change the uploaded file have them click a button and display the FileUpload control again.
This is how gmail does it.
You could wrap the drop down lists in their own update panel (either a separate panel, or a nested panel).
That would sidestep the problem neatly because only the panel with the drop down lists would be re-rendered when their events fire.
You may have to control which triggers cause which kinds of postback for the panels though, and you may have to set the update mode to conditional and manually manage when each panel updates. That depends on how you have the page arranged and all though. Most of the time though, you don't have to do anything special when using multiple panels.
The FileUpload provides a Property for the filename. Just cache it.
UploadedFile.FileName or something like this

Categories

Resources