C# method skipping over java script call - javascript

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

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.

Why doesn't my input in my SharePoint WebPart changes value?

I am trying to change the value of an hidden input every n seconds with a timer in my webpart.ascx.cs to retrieve the value later on in JavaScript, but the value never seems to change. Can you help me figuring out why?
Here's an exemple of what I'm trying to do :
//Initialising the timer
protected void Page_Load(object sender, EventArgs e)
{
Timer timer = new Timer(10 * 1000);
timer.Elapsed += new ElapsedEventHandler(changeValue);
timer.Start();
}
private void changeValue(Object source, ElapsedEventArgs e)
{
myInput.Value = "Changed Value";
}
Then in my ascx I have this input:
<input id="myInput" type="hidden" runat="server" />
If I call changeValue in Page_Load, the value of the input does change, but when it is called afterward with the timer, the value stays the same in the Javascript side.
//Work for the first time, but not when the timer elapsed.
var myInputValue = document.getElementById("myInput").value;
Thanks for your help.
Your timer code, and the Timer object, are running in server side code. Once the page has loaded, the server side code cannot change the client side HTML. If you want the tag to get updated every n seconds/milliseconds, then you should be using client site Javascript setTimeout(function, milliseconds) or setInterval(function, milliseconds).
https://www.w3schools.com/js/js_timing.asp
I looked up the UpdatePanels as #tigerdi suggested me and I was able to update the html from the server side using an ASP Timer. Here the solution that I found :
This Is my UpdatePanel and my timer.
<asp:UpdatePanel id="updatePanel" runat="server" `UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="timer" OnTick="timer_Tick" Interval="10000" runat="server"></asp:Timer>
<input id="myInput" type="hidden" runat="server" />
</ContentTemplate>
Then with the event timer_Tick, I can change the value of my input and then call the UpdatePanel Update() function like so
protected void timer_Tick(object sender, EventArgs e)
{
myInput.Value = "Changed Value";
updatePanel.Update();
}

Send Command.Value via Javascript to codebehind

I am fairly new to ASP.Net and I am stuck.
If my Hyperlink is clicked a Command.Value should be sent to the server. After getting that Command.Value the code behind should check if it is right and redirect to a specific site otherwise just reload the page.
Here is my Hyperlink:
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.FormServer.Command.value =
'test';document.FormServer.submit();"
>Test!!</asp:HyperLink>
First of all I want to ask if my Hyperlink is right. Furthermore I am a bit stuck on the code behind regarding where I need to insert my If statement.
I believe it's much easier to send a parameter by GET in the url of your link. But if for any reason you want to do it by post and using javascript then try this.
Web form: param1 is a hidden field which value will be set using Javascript. When the form is submitted the hidden field is posted with the form.
<form id="FormServer" runat="server" >
<input type="text" id="param1" name="param1" style="display:none;" />
<div>
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.getElementById('param1').value = 'test';document.forms['FormServer'].submit();"
>Test!!</asp:HyperLink>
</div>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
string param1Value = Request["param1"];
if (param1Value == "test")
Response.Redirect("~/Default.aspx");
else if(param1Value == "lost")
Response.Redirect("http://www.google.com");
}
In the code behind it might be useful to check this.IsPostBack. That tells you why the page is being loaded. If it's because the link was clicked then IsPostBack will be true.

How to get confirmation of an action in a web page?

On an ASPX page I have a "Delete" button that is wired up to a method that calls for the current record to be deleted. The button is wired up in this way:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click" />
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
I want to interrupt the delete action with a confirmation dialog, and if it is confirmed then the delete method is called. Presumably I would put an OnClientClick method in there.
OnClientClick="confirmDelete();"
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
if (confirm(msg)){
// Do something here that causes the delete method on the server to be called
}
}
</script>
This raises an OK/Cancel dialog, and clicking Cancel obviously leads to nothing happening, but what if OK is clicked? How is the Delete method on the server to be called? I suppose that I could do a window.open onto a page that did the actual delete, and I can do that, but is there a way to submit to the server-side delete method from JavaScript?
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this?";
return confirm(msg);
}
</script>
And make sure this attribute is on your button.
OnClientClick="return confirmDelete();"
Confirm returns true if the user clicks yes. It returns false if the user hits no. So you just return that, and it will automatically proceed to the server side function if the client side function returned true.
The javascript confirm will not call the server method if the user cancels. If the user clicks ok, the javascript confirm would allow the button to send its request to the server.
You don't need to worry about opening a new page, etc.
Sample 1:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirm('This will delete this AR Contact. Are you sure you wish to do this?');" />
And leave your server-side code the same.
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
Sample 2:
If you have multiple items that can raise the same confirmation message, go ahead and do it the way you had it. However, it would look like this:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirmDelete();" />
And the javascript:
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
return confirm(msg);
}
</script>
When you return the confirm's result, it should be seen by ASP.NET's postback javascript. If confirm or your confirmDelete method returns false, then the postback should be skipped.

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.

Categories

Resources