Value set using JavaScript is not persisted on Postback - javascript

I have two list controls in my asp.net page and am populating the second list control using javascript. Problem is the script executes and i can see the value moved from first list box (ConfiguredOrgListBox) to second list box(SelectedOrgListBox) but when i try to save using submit button i find my second list as empty and first list box as it was earlier. Below is the script and mark up.
//call this method to register the script
private void CreateMoveOrganizationScript(StringBuilder sb) {
sb.Append( #"<script language=javascript type=text/javascript>;
function moveOrganisation() {");
sb.Append( #"var source = document.getElementById('"+ ConfiguredOrgListBox.ClientID +#"');
var target = document.getElementById('"+SelectedOrgListBox.ClientID+ #"');
if ((source != null) && (target != null)) {
var newOption = new Option();
newOption.text = source.options[source.options.selectedIndex].text;
newOption.value = source.options[source.options.selectedIndex].value;
target.options[target.length] = newOption;
source.remove(source.options.selectedIndex) ;
}
} </script>");
}
Markup
<asp:Label ID="ConfiguredOrgLabel" runat="server" Text="Available Organizations"></asp:Label><br />
<asp:ListBox ID="ConfiguredOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
<input id="MoveOrgRight" type="button" value=">>" onclick="moveOrganisation()" />
<asp:Label ID="SelectedOrgLabel" runat="server" Text="Selected VNA Organizations"></asp:Label><br />
<asp:ListBox ID="SelectedOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
Please let me know what I am doing wrong
Regards,
JeeZ

According to this, it's because the list box doesn't post back to tell the back-end that it's changed. They use a hidden field which holds info on what changes were made with JavaScript and then on postback it updates the back-end.

You need to process these changes during postback. When postback happens ASP.NET engine loads control's data from view state and it doesn't know that client modified values using javascript, so you should manually extract those values from Request.

Related

How to pass data from (front-end) .aspx to (back-end) .aspx.cs using hidden filed

I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.

how to disable button after first click in javascript

I am new to C#. I have a save button inside InsertItemTemplate. I have used the following code to disable the button after first click in java script but its not even working for the first click please help me.
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="this.disabled='true';return true;" />
You are modifying the "disabled" property of the DOM object on the browser, but the button will do a post back to the server when it's clicked, so any change to the DOM will be lost.
On the function where you handle the command "Add" in your server code you must retrieve the button from the InsertItemTemplate and set its "Enabled" property to false, that will disable the control from the server side.
If you want to avoid multiple clicks while the page has not been reloaded then you need a client function to avoid this, something like this:
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="return checkEnabled(this);" />
<!-- somewhere in your page -->
<script>
function checkEnabled(item)
{
if(item.disabled != 'true')
{
item.disabled = 'true';
return true;
}
return false;
}
</script>

Set enter key behavior on aspx form

Have the need to alter the behavior of pressing enter on my aspx page based on the last control that was interacted with. I have two textboxes and a dropdown. Each one of those controls has a corresponding button that takes the input and applies it to other fields on the page. Much like adding options to a master part.
Example: If button2 is pressed, the option in textbox2 would be applied, but not the option in textbox1, or the dropdown. The page is refreshed, and the user can continue to select options.
How would I alter the page to allow the user to type in text in a textbox and then hit enter to activate the code for the corresponding button. I've tried various js to set the page default, but have been unsuccesseful in changing this on the fly.
You can use ASP.Net Panel control's DefaultButton to accept enter key.
http://geekswithblogs.net/ranganh/archive/2006/04/12/74951.aspx
<asp:Panel ID="pnl1" runat="server" defaultbutton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" defaultbutton="Button2">
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
</asp:Panel>
Set event listeners for a user modifying the inputs and set a reference to the proper button. Then have a listener for the enter button to trigger submitting the referenced button. You didn't mention jQuery or any JS framework so I'll try writing it generally for plain javascript, I'd recommend using a framework though for cross browser support.
var myButtonId = null;
var storeInputButtonId = function(buttonId) {
return function(event) {
myButtonId = buttonId;
};
};
//Do following for inputs, or your preferred event binding pattern
var fld = document.getElementById('myInputId');
//Statically refer to button id or replace with suitable algorithm
var inputButtonId = "";
if (fld.addEventListener) {
//Could bind to other events with logic based on input element type
fld.addEventListener('keyup',storeInputButtonId(inputButtonId), false);
}
//Method to trigger the button click event
function submitData(event){
//Watch for the enter button
if ( event.which == 13 ){
document.getElementById(myButtonId).click();
}
}
//Bind the listener to the enter button
var bodyElement = document.getElementsByTagName('body')[0];
if (bodyElement.addEventListener) {
bodyElement.addEventListener('keydown',submitData, false);
}

ASP.NET UpdatePanel and Javascript __dopostback

I'm calling a partial postback from javascript like so:
function GetPolicyClick()
{"__dopostback('UpdatePanel1', 'PostCall')";}
It does 1/2 of what I need it to. It does call a partial postback, just for my UpdatePanel.
Now the tricky part. I'm trying (somehow) to reference the second argument of __dopostback in my code behind. This does not work:
Private Sub UpdatePanel1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdatePanel1.Load
Dim MyArg As String = Request("__EVENTARGUMENT")
End Sub
I just get an empty string.
Of course, what I'm trying to do might be completely wrong (as with everything else I try to do with ASP). I'm suspecting that my codebehind is grabbing the event argument from the page instead of the panel, but I really don't know, Any ideas?
If you want to put some value inside _EVENTARGUMENT you should do this with javascript before sending form by _doPostBack('UpdatePanel1','') because __EVENTTARGET is hidden field and in your html document it looks like this:
<input type="hidden" value="" id="__EVENTARGUMENT" name="__EVENTARGUMENT">
I recommend you to do something like this:
function setArgAndPostBack() {
var arg = document.getElementById('__EVENTARGUMENT');
var arg = document.getElementById("__EVENTARGUMENT");
arg.value = 'something you want to put to server';
__doPostBack('UpdatePanel1', '');
}
If you use jQuery it would be shorter:
function setArgAndPostBack() {
$("#__EVENTARGUMENT").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
If it doesn't work I would like to suggest you to put one hidden field inside Update panel:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:HiddenField ID="hdnData" value="" runat="server" />
<!-- your content goes here -->
</ContentTemplate>
</asp:UpdatePanel>
And then do the same work like above:
function setArgAndPostBack() {
//Here hidden field is filled with your data
$("#<%=hdnData.ClientID%>").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
In first scenario you are able to get __EVENTARGUMENT in server side:
String args = Request["__EVENTARGUMENT"];
If first scenario doesn't work you can use something like that:
String args = hdnData.Value;//This works even in Page_Load function.

Using Jquery in UserControl with MasterPage

I can't seem to get Javascript to work on my usercontrol. All I want to do is count the characters in a mulitline textbox (which adds another level of complexity). I want to count the characters and display them in a label.
I have my javascript in a .js file included in the MasterPage:
function textCounter(field, countfield, maxlimit) {
var output = document.getElementById(countfield);
if (output == null) { return; }
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
output.value = maxlimit - field.value.length;
}
My UserControl has little code:
<script type="text/javascript" language="javascript">
if (typeof contentPageLoad == 'function') {
var outputField = $("[id$='lblCharacterCount']");
}
</script>
<asp:TextBox ID="txtMyTest" runat="server" Height="75px" CssClass="form-field full" TextMode="MultiLine" MaxLength="140"
onkeyup="textCounter(this, outputField, 140);" onkeydown="textCounter(this, outputField, 140);" ></asp:TextBox>
<asp:Label ID="lblCharacterCount" runat="server"></asp:Label>
outputField is always null when it tries to execute the function. I've tried adding it(the script on the UserControl) in a scriptblock in the UserControl PageLoad, PreRender and PreInit. Nothing seems to work.
UPDATE:
I was able to get UserControl Javascript working w/o an UpdatePanel. That was the problem, the UserControl was in an UpdatePanel. I've given up on using a Usercontrol in an updatepanel with JS unless someone can offer any advice.
Try changing the selector to something like this:
var outputField = $("#<% lblCharacterCount.ClientId %>");
The ID you set on the control is usually not the ID that gets assigned to it in the HTML that is generated. Using the ClientId property, will get you that HTML ID.
Of course I haven't used ASP.NET in a while so this answer might be worthless.

Categories

Resources