Send Command.Value via Javascript to codebehind - javascript

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.

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 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.

Send JavaScript variable to asp.net webforms code-behind is always empty

I was using this SO answer as a reference for sending a JavaScript variable to my server side. However when I implement that solution everything comes up correctly in the JS alert(), but the value of my hidden field when I hit the server is always empty.
JavaScript and Html:
<script>
function rblSelectionChange()
{
var selection = $('#inAction input:checked').val();
var stuff = $('#<%= clientSelection.ClientID %>').val(selection);
alert(stuff.val());
}
</script>
<asp:HiddenField ID="clientSelection" runat="server" />
<div class="row-fluid">
<asp:RadioButtonList runat="server" ID="inAction" ClientIDMode="Static">
<asp:ListItem onClick="rblSelectionChange();" Value="RuEp" Text="I remember my <b>username</b>. Please email me a new <b>password</b>." />
<asp:ListItem onClick="rblSelectionChange();" Value="ReEu" Text="I remember my <b>email</b>. Please email me my <b>username</b>." />
<asp:ListItem onClick="rblSelectionChange();" Value="ReEup" Text="I remember my <b>email</b>. Please email me my <b>username</b> and a new <b>password</b>." />
</asp:RadioButtonList>
</div>
On the submit event of the page I try to grab the value and it is empty:
protected void btnActionSelect_Click(object sender, EventArgs e)
{
string selection = clientSelection.Value;
...snip...
}
Any idea what I am missing?
Update
I have tried to change my hidden field to a pure html one, not the asp: control.
<input type="hidden" id="clientSelection" name="clientSelection" value="" />
I have modified the code-behind as follows:
private string _selection = "";
protected void Page_Load(object sender, EventArgs e)
{
//_selection = clientSelection.Value.ToString();
if (IsPostBack)
_selection = Request.Form["clientSelection"];
}
I am still getting nothing for the value Request.Form["clientSelection"]. Important note however is it works in Chrome, FF, and IE10. The browser I am trying to get it to work in is IE 7 8 and 9. I am fully stumped.
Update 2
Per request, here is the source of the page when I inspect it in IE10 (with browser and document mode set to IE7)
<DIV id=ctl00_cphBodyWithForm_htmActionSelect class=row-fluid>
<P class=lead>Can't access your account? Please select from the following options: </P>
<SCRIPT>
function rblSelectionChange()
{
var selection = $('#inAction input:checked').val();
var stuff = $('#ctl00_cphBodyWithForm_clientSelection').val(selection);
alert(stuff.val());
}
</SCRIPT>
<INPUT id=ctl00_cphBodyWithForm_clientSelection type=hidden name=ctl00$cphBodyWithForm$clientSelection jQuery191034119593101524303="7">
<DIV class=row-fluid>
<TABLE id=inAction border=0>
<TBODY>
<TR>
<TD><INPUT onclick=rblSelectionChange(); id=inAction_0 type=radio value=RuEp name=ctl00$cphBodyWithForm$inAction jQuery191034119593101524303="8"><LABEL for=inAction_0>I remember my <B>username</B>. Please email me a new <B>password</B>.</LABEL></TD>
</TR>
...snip...
</TBODY>
</TABLE>
</DIV>
<DIV class=span12>
<A class="submitButton roundedBR" href="javascript:__doPostBack('ctl00$cphBodyWithForm$ctl00','')">Continue > </A>
</DIV>
</DIV>
Run your HTML through a validator. If your form values aren't posting in certain browsers, it sounds like you have invalid HTML, and that is the source of your problem.
Once you fix the HTML issue, you can get rid of that JavaScript and simply use the value of inAction.
W3C Markup Validation Service
You mentioned that you had weird closing form tag issues. A form cannot be placed within a form, so perhaps that was the root of your problem.

How to fire a button click event from JavaScript in ASP.NET

How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.

Categories

Resources