ASP.NET UpdatePanel and Javascript __dopostback - javascript

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.

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.

C# method skipping over java script call

I have an ASP button that has an event listener attached to it. When pressed it calls the C# method and executes whatever code I may have within it.
I have a javascript function I want to call when the listener first executes. However, C# completely skips over the function call and moves on to the lines below it.
Here's the question: Why is it skipping over the call? And when I isolate just the call, ( have nothing in the method other than the call) IT WORKS. The very second I put another line of code below it, it stops being called. Any help would be greatly appreciated.
Here is the ASP button.
<asp:Button ID="crapJim" runat="server" Text="RateTest" OnClick="crapJim_Click"/>
And here is the C# Method
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
/* ClientScript.RegisterStartupScript(GetType(), "hwa", "getSessionName();", true);*/
string s = hfRaterName.Value;
Console.Write(s);
string stop = "";
}
Currently have the ClientScript commented out and trying the ScriptManager. Both work individually, but not when other code is with it. What I mean by that is:
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
}
Just this alone will work, but any other code with it, it will no longer fire. C# skips over it.
Oh and here is the Javascript code I am using.
function getSessionName() {
var hfRaterName = prompt("Please enter your session name");
hfRaterName.value = hfRaterName;
}
There's an easier way, if you don't have to use RegisterStartupScript.
.aspx:
// OnClientClick will call your javascript function first, then the code behind.
<asp:Button ID="btnPrompt" runat="server" Text="Prompt"
OnClientClick="doPrompt();"
OnClick="btnPrompt_Click" />
<br />
<asp:Label ID="lblPromptResult" runat="server"></asp:Label>
<br />
<asp:HiddenField ID="hfPrompt" runat="server" />
<br />
<script>
function doPrompt() {
document.getElementById("hfPrompt").value =
prompt("Please enter your session name");
}
</script>
Code behind:
protected void btnPrompt_Click(object sender, EventArgs e)
{
lblPromptResult.Text = hfPrompt.Value;
}
In the case anyone else comes across this same problem. I took wazz's advice and used the OnclientClick along with Onclick. Executing the Javascript first rather than having the C# call the Javascript.
//This is the HiddenField used to capture the users identified session name
//which I then store in a DB and use in a few other related pages.
<asp:HiddenField ID="HiddenField1" ClientIDMode="Static" runat="server" />
//This is the ASP button used to call both the Javascript and C# code behind
<asp:Button ID="btnRateBeazely" ClientIDMode="Static" runat="server" CssClass="btnbig" Text="Rate Beazley" OnClick="btnRateBeazely_Click" OnClientClick="getSessionName();" />
//The Javascript is simple, but does exactly what I want it to. DB has character
//limit to 50 so I ensure the user can't input higher than that. Assign the input
//to the hiddenfield ID and off we go.
function getSessionName() {
var SessionSet = prompt("Please enter your session name");
while (SessionSet.length > 49) {
alert("You have too many characters. Please enter again.")
var SessionSet = prompt("Please reenter your session name");
}
document.getElementById("HiddenField1").value = SessionSet;
}
//In the code behind I just assign a new string variable to the hidden field value

How to pass javascript function's output to asp button CommandArgument

I want to pass java script function value to command argument of button and want to get in EditGuest data method of my cs page.
Here is the EditGeuest function
function EditGeuest(){
var gstDetails = document.getElementById('<%#cmbGuestName1.ClientID %>');
var guestID = gstDetails.value;
}
Here is the button code
<asp:Button ID="Editbtn" OnClientClick="EditGeuest() OnClick="EditGuestdata" CommandArgument=guestID runat="server" Text="Edit" />
You want to use this:
document.getElementById('Editbtn').CommandArgument = guestID
Your button tag must already contain the attribute CommandArgument with or without a value.

Accessing value of hidden variable in Javascript wiht VB

I tried the following code but did not succeed.It would be great if you could guide me. I was trying to test using a simple "Hello". In the actual program I would assign a string value to the hidden field.
I get an Alert box ( using this to test whether the value is accessible in javascript ) but with no values.
Server Side
ivar.Value = "Hello"
Javascript
<script>
function getval() {
var v = document.getElementById('<%= ivar.ClientID%>').value;
alert(v)
}
</script>
Form
<asp:Button ID="Button1" runat="server" Text="CALCULATE" onclientclick="getval()" />
<asp:HiddenField ClientIDMode="static" id="ivar" runat="server" Value=""/>
Let us say you have a public variable on server side:
public string iVar = "Hello";
You can directly add it to your javascript as below:
<script>
function getval() {
var v = <%=iVar%>;
alert(v);
}
</script>
Hope this helps.
Your call to find the client id in your script block may be trying to find the hidden field before it exists. try moving the script to the bottom of the page just before you close your body tag and see if that helps.

Value set using JavaScript is not persisted on Postback

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.

Categories

Resources