OnClientClick isn't firing for ImageButton - c#

I have an ASP.NET ImageButton that OnClientClick() is supposed to fire a js function that reads the values from a two text fields, send it to a server-side WebMethod. With the WebMethod sending it to another entity method which handles the storage. I've tried debugging by setting breakpoints in the WebMethod and storage method on the serverside but neither is getting reached. I then tried setting a breakpoint on client-side using the Mozilla Firebug tool. The js function never gets called and the page just refreshes. I set a breakpoint in another js function and it was traced perfectly. Any help?
ASP
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="javascript:handle(); return false">
</asp:ImageButton>
JS
function handle() {
window.$get("#" + "<%= btnSend.ClientID %>").click(
function () {
var txtVC = window.$get("#" + "<%= txtVC.ClientID %>").value();
var txtMsg = window.$get("#" + "<%= tbMgSend.ClientID %>").value();
if (txtVC != "" || txtMsg != "") {
window.PageMethods.SendMsg(txtVC, txtMsg, txtMessageResult);
return window.$get("#" + "<%= lblMessageStatus.ClientID%>").value("SUCCESS"),
alert("SUCCESS");
}
else {
return alert("Text Message is Empty!");
}
});
}
function txtMsgResult(result) {
if (result != '') {
window.$("#" + "<%= lblMessageStatus.ClientID %>").innerHTML = result;
alert("SUCCESS");
}
}
I've tried the following:
* OnclientClick with and without return
* $get with and without concat(+)
* changing the server-side to a method instead of web method and that also didn't fire

Have you tried it without the return false?
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="handle()">
</asp:ImageButton>

Maybe it doesn't work because it autoPostBack.
I'm not sure there is a way to turn it off in an ImageButton. Why not use a HTML control instead ?

Related

cannot get the session on vb page when it set using jquery

I have a img button. When it is clicked, I set the session value using jquery. however I cannot get the session on vb code behind. My process is like that after the user click the image, I set the session. When the user open popup page and return the page. I need to check the session to do something. However in the vb code, the session is nothing. Would some one tell me how to do it.
The below code call the function:
<asp:Image ID="img" runat="server" onclick="SetSession(hdID);" ImageUrl="pic_bottle.gif" />
The jquery script:
function SetSession(hdID) {
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
$.session.set('UpdateProdOrder', -1);
}
else {
var hdProdID = $('#hdProdID').val();
$.session.set("UpdateProdOrder", hdProdID);
}
alert($.session.get("UpdateProdOrder"));
}
The vb code behind never get the session
If Not Session("UpdateProdOrder") Is Nothing Then
'do something
updateOrder()
end if
The localStorage and sessionStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
These values are maintained on the client side, but you are trying to retrieve it on the server side. session variables are server side
Solution:
Method 1:
You'd have to have a little ajax call to talk to the server to set it.
please check it out
Method 2 :
Assigning the ASP.NET Session Variable using Javascript.
<script type="text/javascript">
function SetSession(hdID)
{
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
'<%Session["UpdateProdOrder"] = "' + -1+ '"; %>';
}
else {
var hdProdID = $('#hdProdID').val();
'<%Session["UpdateProdOrder"] = "' + hdProdID+ '"; %>';
}
alert('<%=Session["UpdateProdOrder"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetSession()
{
var updateProdOrder= '<%= Session["UpdateProdOrder"] %>';
alert(updateProdOrder);
}
</script>
You cannot change a server side Session object with javascript directly. You need to send it to the server somehow. This can be done by changing the image to an ImageButton and do a PostBack to modify the Session object. But since you seem to have some data in hdID. You cannot send that to the server with a ImageButton alone, you'll need a HiddenField
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSession(hdID);"
ImageUrl="pic_bottle.gif" OnClick="ImageButton1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript">
var hdID = 'test';
function SetSession(hdID) {
$('#<%= HiddenField1.ClientID %>').val(hdID);
}
</script>
And then in code behind
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["UpdateProdOrder"] = HiddenField1.Value;
Label1.Text = string.Format("Session value is now '{0}'", Session["UpdateProdOrder"]);
}
You could do this also without the javascript SetSession, but that depends on where and when hdID is used on other parts of the page.

Asp.Net CustomValidator still invalid after ClientValidationFunction

I have a ListView whose template has a LinkButton with a CustomValidator.
<ItemTemplate>
<div>
<asp:LinkButton runat="server" ID="_linkButtonDelete"
ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
CausesValidation="true" />
<asp:CustomValidator runat="server" ClientValidationFunction="validateDelete"
ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
data-itemId='<%# DataBinder.Eval(Container.DataItem. "Id") %>'>*</asp:CustomValidator>
</div>
</ItemTemplate>
In validateDelete function I perform a synchronous AJAX request to determine whether the specific item can be deleted.
function validateDelete(sender, args){
var itemId = sender.dataset.itemid;
$.ajax({
async:false
// other settings omitted
success: function(jsonResult){
args.IsValid = jsonResult.CanDelete;
}
});
}
However, when I click on a button for which validateDelete function sets args.IsValid = true (I checked the response with Fiddler and by debugging the function) the link does not trigger a postback and the validator is invalid (i.e. I can see the red * near the button).
Why does the validator remain invalid?
i implement your scenario, and cause i do not know your code behind, i sent my request to a ashx handler :
$.ajax({
async: false,
url: "Handler1.ashx",
success: function (jsonResult) {
args.IsValid = jsonResult == "False" ? false : true;
}
});
and this is handler1.ashx implementation :
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(true); // this return value was changing manually
// to test both true and false situations
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
everything work fine, probably the problem is where you assign args.IsValid, try to cast jsonResult.CanDelete if its not boolean before set args.IsValid, like something i have done using iif, may your problem be solved...
i do not know, whether this javascript codes you copy here is differ with its original on your page... but after async:false u need a ,
Thanks to hints from #Șhȇkhaṝ and #am1r_5h and the suggests from here, namely
setting args.IsValid at the end of the code
I was able to perform validation on client by refactoring the validateDelete function into this:
function validateDelete(sender, args){
var itemId = sender.dataset.itemid;
var isValid; // <- declare outer scope variable to hold the result
$.ajax({
async:false
// other settings omitted
success: function(jsonResult){
isValid = jsonResult.CanDelete; // <- set the result of ajax call
}
// Set args.IsValid at the end of the function.
args.IsValid = isValid;
});
}

How to get label value which loads with javascript

I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.

How to get data from serverside from JavaScript in vs2010

I call another page with an id, which returns the data based on id. I need the result value in JavaScript.
Then I need to bind the result to current page content area and display it to the user.
Initially, the user clicks one link in current page, then the id of the link should be passed to another page, and processed some function and get result from db.
I want to display the result in current page.
I am using vs2010. How can I do this?
So, you already have solved your asp.net part (you have the page, right?).
What you can do is use jquery and make an ajax call to that page and process the result. If your page returns a the information in json or xml format, it's easy to use it to upgrade your current document in the browser.
Here you will find the documentation and some samples of Jquery ajax: http://api.jquery.com/jQuery.ajax/
Hope it helps.
function ajaxCall(id_from_your_page){
$.ajax({
type: "POST",
url: '/service.asmx/your_method',
data: { 'id', id_from_your_page },
dataType: "application/json; charset=utf-8",
success: function(result){
alert("i got your result: " + result);
}
});
}
the above code is better as you will use JQuery and POST method.
you may also like this-
function sendRequest(id) {
var xmlObj = null;
if(window.ActiveXObject) {
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlObj = new XMLHttpRequest();
}
if(!xmlObj) return;
var location = "http://localhost:8080/myapplication/mypage?id="+ id;
xmlObj.open("GET", location, true);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState==4 && xmlObj.status==200) {
doSomethingWithTheResponse(xmlObj.responseText);
}
}
xmlObj.send(null);
}
function doSomethingWithTheResponse(responseText) {
// write your own code to handle the response from the page.
}
All the best :)
You can get the Id/Data from other pages or Db like this....
<asp:LinkButton runat="server" Text='<%#Eval("Title")%>'OnClick='javascript:ShowEventDetails'CommandArgument='<%#Eval("EventID").ToString()%>);'/>
or
onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'
ASPX:
<asp:Button ID="btnget" runat="server" Text="Create WR" onClientClick="<%# GetPopupScript() %>" />
Code-behind:
protected string GetPopupScript() {
return string.Format( "javascript:popUp('popup_createWR.aspx', '{0}', '{1}')", Eval( "dvc_nm" ), Eval( "data_orgtn_yr" ) ); }
or try this...
<asp:LinkButton ID="LinkButton5" OnClientClick='<%# "return fun1(""" + Eval("mid") + """);"%>' runat="server"><%#Eval("mname")%></asp:LinkButton>

Javascript link with onClick event

I am using a third-party shopping cart from http://simplecartjs.com/ .
For a normal checkout I can use:
<a href="javascript:;" class="simpleCart_checkout" >Checkout</a>
And it works. But I need to add some server-side functionality and don't know how to go about this. The code inside the javascript file where the simpleCart_Checkout class is stored is as follows:
me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart.checkout , "click");
EDIT: and this:
me.checkout = function() {
if( me.quantity === 0 ){
error("Cart is empty");
return;
}
switch( me.checkoutTo ){
case PayPal:
me.paypalCheckout();
break;
case GoogleCheckout:
me.googleCheckout();
break;
case Email:
me.emailCheckout();
break;
default:
me.customCheckout();
break;
}
};
So I tried doing it using a button calling the method directly:
<asp:Button ID="CheckoutButton" runat="server" Text="Checkout"
onclick="CheckoutButton_Click" OnClientClick="Checkout()" />
<script type="text/javascript">
function Checkout() {
javascript: simpleCart.checkout;
}
</script>
Which calls the server-side but doesn't call the javascript link. I am new to asp.net and javascript so don't really know any other ways of how I can do this, please help.
try this:
<asp:Button ID="CheckoutButton" runat="server" Text="Checkout"
onclick="CheckoutButton_Click" OnClientClick="javascript:Checkout();" />
<script type="text/javascript">
function Checkout() {
simpleCart.checkout();
return true;
}
</script>
Edit:
you want your scripts being called after the server event. then you'll need to call your Checkout function at the end of "CheckoutButton_Click".
Page.ClientScript.RegisterStartupScript(Page.GetType(), "calling checkout", "<script>CheckOut();</script>", true);
simpleCart.checkout() doesn't got a chance to do redirect, as OnClientClick returns true and post back happens.
That should be enough.
function Checkout() {
simpleCart.checkout();
return true;
}
You can call your javascript from Server side.
Page.RegisterStartupScript will assists you to fire javascript from code behind.
Page.ClientScript.RegisterStartupScript(Page.GetType(), Guid.NewGuid().ToString(), "alert('hello')", true);

Categories