how to pass Bound value (asp.net control ) to a jquery - javascript

Let me explain what I am trying to do.
I have a asp.net gridview and one of the bound columns is a label field showing count, say 100, but in the code behind I have the spilt up of how I got that value. So on hover over the label I want to show something like labor = 30, material = 50, cost = 20
This is my aspx code
<asp:TemplateField HeaderText="Total Cost" ItemStyle-HorizontalAlign=Center ItemStyle-VerticalAlign=Middle>
<ItemTemplate>
<asp:Label ID="Label2" Text='<%# Eval("TotalCost")%>' runat=server></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Question 1:
can i override tooltip template just like WPF/silverlight to show this infromation
Question 2
if i need to use jquery to show a small window as tooltip on hover over, then how do i pass the details like labor = 30, material = 50, cost = 20 to the jquery
question 3
can i do this in javascript
<asp:Label ID="Label2" Text=MYJavascriptFunction('<%# Eval("TotalCost")%>') runat=server onmouseover ></asp:Label>
i.e first bound value will go to my javascript function and it will process something and return a text that will be used in the asp:Label Text.
Please point me in right direction.

You should be able to use the ToolTip property of the Label control, and bind it to display your data:
<asp:label ID="Label2" Text='<%# Eval("TotalCost")%>' ToolTip='<%# String.Format("Labor={0}, Material={1}, Cost={2}", eval("labor"), eval("material"), eval("cost")) %>' runat="server"></asp:Label>
This is rendered as the "Title" property of the <span> tag that is output by the Label control.

If you want to create your own custom tooltip, here's a basic implementation:
You can create an attribute on your <asp:Label> called data-costfactors that can hold the information to display on hover (using jQuery) and add the CssClass="total" attribute to the label as well
<asp:TemplateField HeaderText="Total Cost" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
CssClass="total"
Text='<%# Eval("TotalCost")%>'
data-costfactors='<%# Eval("CostFactors") %>' />
</ItemTemplate>
</asp:TemplateField>
Where CostFactors in your datasource looks something like "labor = 30, material = 50, cost = 20"
Setup your tooltip html element like so:
<div id="tooltip"></div>
Style the tooltip div with some simple CSS:
#tooltip {display:none;position:absolute;border:solid 1px;background:#fff;}
Then with jQuery you can setup your tooltip with the data-costfactors attribute value like so:
$(function () {
var $tooltip = $('#tooltip');
$('.total').hover(function (e) {
var $this = $(this);
$tooltip.html($this.data('costfactors')).show();
}, function () {
$tooltip.hide();
}).mousemove(function (e) {
$tooltip.css({
top: (e.pageY + 15) + "px",
left: (e.pageX + 15) + "px"
});
});
});

Related

gridview row delete confirmation box

I need to show a delete conformation box on Gridview delete. with OnClientClick confirmation box, I am showing a simple Internet explore box for delete confirmation. Is it possible to show a fancy box for this. below is my JavaScript code that exists inside the gridview code:
OnClientClick="return DeleteItem();"
Below is my Gridview
<asp:GridView ID="grdShoppingCart" runat="server" AutoGenerateColumns="false" class="ui-responsive table-stroke ss-table ui-search-result-table" DataKeyNames="CartID" AllowPaging="false" PageSize="5" GridLines="None" OnRowDataBound="grdShoppingCart_RowDataBound" OnRowDeleting="grdShoppingCart_RowDeleting">
<Columns>
<asp:BoundField DataField="CartID" Visible="false" HeaderText="CartID" />
<asp:BoundField DataField="item" HeaderText="Item" HeaderStyle-Font-Bold="true" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="250px" ControlStyle-CssClass="ss-row" />
<ItemTemplate>
<asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/Images/delete1.png" title='Remove' CommandName="delete" OnClientClick="return DeleteItem();" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my Javascript function:
<script type="text/javascript">
function DeleteItem() {
if (confirm("Delete this Location?")) {
return true;
} else {
return false;
}
}
</script>
above code is showing this confirmation window:
I want to show something like this:
any help will be apprecaited.
It's not possible to add css to a confirm box. You can implement your own JavaScript popup.
Alternatively there are many plugins that can do this. One of the most popular JQuery plugins is JQuery UI dialog https://jqueryui.com/dialog/#modal-confirmation
As an as illustration for integrating JQuery UI Dialog with an ASP.NET Gridview, try something like:
<asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/Images/delete1.png" title='Remove' CommandName="delete" class="button-delete" />
You don't need OnClientClick="return DeleteItem();"
The css class can be used as a reference for an onclick event.
JavaScript:
$(function() {
// Create click handler
$('.ui-search-result-table').on('click', 'button-delete', function(e) {
e.preventDefault($(this)); // $(this) should be a reference to imgbtnDelete
showDialog();
});
// Create the dialog popup
function showDialog(button) {
$("#dialog-confirm").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Remove": function() {
$(button).click(); // This should click imgbtnDelete
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
});
HTML for popup
<div style="display: none;">
<div id="dialog-confirm" title="Remove Item?">
<p>Are you sure you want to remove this item?</p>
</div>
</div>
Note: This example is for illustration purposes. You will need to have a play around with your solution to get it working.

JqueryUI Confirmation dialog on ASP.Net GridView Button

I have a Gridview with buttons for removing data rows. I'm trying to implement a modal popup via jQueryUI Dialog so that after clicking "Remove Data" the user gets prompted and if they click yes, the row gets removed, if no, nothing happens. It seems that if I don't add a "return false" to the onClientClick, the row will be removed as soon as the button is clicked, regardless. If I include return false, I'm not sure how I can get the gridviewrow command to actually happen. Here are some current snippets:
In script tag:
function ShowPopup() {
$(function () {
var message = "Are you sure you want to Remove Data?";
$("#dialog").html(message);
$("#dialog").dialog(
{
title: "Data Removal Confirmation",
buttons: {
Yes: function () {
return true;
},
No: function () {
$(this).dialog('close');
}
},
modal: true
});
});
}
Dialog Div:
<div id="dialog" style="display: none">
Gridview Button:
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:Button
ID="btnRemove"
runat="server"
Text="Remove Data"
CssClass="inherited, RemoveData"
CommandName="RemoveData"
Style="white-space: normal;"
OnClientClick="javascript: ShowPopup();return false;"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
Codebehind:
else if (e.CommandName == "RemoveData")
{
int affected = 0;
affected = DAL.RemoveFileUploadItem((Guid)Session["UserId"], UploadId.ToString());
BindAll();
gv_PostUpload.DataSource = null;
string FileName = UploadId.ToString() + "-" + gvDashboard.DataKeys[index]["FileName"].ToString();
string mypath = Path.Combine(Global.data_directory, #"Watch"); // Server.MapPath("~/Data/Watch/");
string totalfn = Path.Combine(mypath, FileName);
if (File.Exists(totalfn))
File.Delete(totalfn);
DAL.LogActivity("Attempt removing file " + gvDashboard.DataKeys[index]["FileName"].ToString(), Utilities.GetCurrentPageFromURL(), Session["UserId"].ToString());
int affected = 0;
affected = DAL.RemoveFileUploadItem((Guid)Session["UserId"], UploadId.ToString());
if (affected != 0)
{
DAL.LogActivity(gvDashboard.DataKeys[index]["FileName"].ToString() + " removed ", Utilities.GetCurrentPageFromURL(), Session["UserId"].ToString());
}
BindAll();
gv_PostUploadZ.DataSource = null;
plnView.Visible = false;
plnViewZ.Visible = false;
plnErrorView.Visible = false;
}
Here are the modified buttons based on #albert-d-kallal's answer:
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:Button
ID="btnRemove"
runat="server"
Text="Remove Data"
CssClass="inherited, RemoveData"
CommandName="RemoveData"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
<ItemTemplate>
<asp:Button
ID="btnRemove2" ClientIDMode="Predictable"
runat="server"
Text="Remove Data"
CssClass="inherited, RemoveData"
Style="white-space: normal;"
OnClientClick='<%# "ShowPopUp(" + ((GridViewRow) Container).RowIndex + ");return false;" %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
After the above modification, here is what I now am seeing n browser tools when inspecting that the button:
<input type="submit" name="ctl00$mainContent$gvDashboard$ctl02$btnRemove2" value="Remove Data" onclick="ShowPopUp(0);return false;" id="ctl00_mainContent_gvDashboard_ctl02_btnRemove2" class="inherited, RemoveData" style="white-space: normal;">
Ok, first up?
jQuery.ui and MOST web code these days is NON blocking. That means the jQuery.UI dialog DOES NOT halt code. Near all code runs - and runs without blocking (async).
So, if you use anything but the alert() dialog, you can't block code, and return true, or false.
So, what to do?
Well, it means we have to display the dialog, and THEN AFTER the user makes the choice, we have to fire/trigger/click/run code to do the delete.
So, I would suggest that your delete button does NOT run the row index changed, and execute that code. In theory, you would say pass some PK row value to the js on a click. Get the yes/no using the jQuery dialog, and THEN call some code to do the delete.
So, that button can not really return true/false to THEN allow the button code (server side) to run.
I can think of quite a few ways to do this. However, you can trick the grid, and have jQuery "click" on the button AFTER you determined yes (ok) or cancel.
This quite much means we need a "differnt" button. But, we could just "hide" the existing delete button (but leave it in place), and simply place our javascrip button right below that button.
So, lets hide your button with style="display:none" (FYI - can't use visible, since that would mean the browser never renders the button).
So, lets do this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button
ID="btnRemove"
runat="server"
Text="Remove Data"
style="Display:none"
CommandName="RemoveData"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
so we style button = none (it will not display). I also removed the CssClass - again since the button is "hidden", we don't care.
Now, lets drop in our button that we REALLY click on!
Lets put it right below above in the markup:
<asp:TemplateField>
<ItemTemplate>
<asp:Button
ID="btnRemove2"
runat="server"
Text="Remove Data"
CssClass="inherited, RemoveData"
Style="white-space: normal;"
OnClientClick='<%# "ShowPopUp(" + Container.DisplayIndex.ToString + ");return false;" %>'
</ItemTemplate>
</asp:TemplateField>
So, above is a dummy button - note the return = false; we don't want it to run any sever side code - and the return = false means no post back occurs.
But, NOTE one big deal? We passed the row index to that click event.
So, our jQuery.ui dialog can now look like this:
function ShowPopUp(ix) {
var message = "Are you sure you want to Remove Data?";
var mydiv = $('#dialog');
mydiv.html(message);
mydiv.dialog({
autoOpen: false, modal: true, title: 'Data Removal Confirmation', width: '30%',
position: { my: 'top', at: 'top+150' },
buttons: {
'Yes': function () {
// first, close the dialog
$('#dialog').dialog('close');
btn = $('#GridView1_btnRemove_' + ix.toString());
btn.click();
},
'No': function () {
$('#dialog').dialog('close');
}
}
});
// Open the dialog
mydiv.dialog('open');
}
Note how now we have code for the ok, and cancel buttons.
Note how we have to close the dialog.
And note that last whopper - we select the button based on the row, and click it.
Now, I not really sure if above is the best. I would perhaps consider NOT using the fake button click - Might have just as well done a js postback and passed the row index with a postback argument. (this would mean in the page on-load event, you would pick this post-back up - you can google _dopostback().
Note also one did not need the "script" in front of the OnClickClick.
But, the above should work.
So, keep in mind:
the jQuery.ui code is NON blocking - it does not wait. When you call it, it runs right though and THEN displays the dialog - the code does not halt, nor is it blocked. As a result, we can't return true, or false (to allow the server side code to run).
If the jQuery.ui dialog WAS blocking, then the return of true/false could be used - but that code does not block/wait.
But, by passing the row index, we ARE able to select the hidden button, and click() fire it. As noted that's somewhat ok of "approaching a kluge" idea here. However, since you KNOW existing code works, that's why I went with the button click trick here.
I used GridView1, as the grid name - change it to what you are using.
Ok, it's a bit hacky, but I was able to use some of #albert-d-kallal's suggestions above, but had to come up with some other code that would anchor the correct rowindex values to the actual buttons that were wired to the .Net event handlers. I did this by just making the "fake/hidden" buttons have a text value of the row index. In order to hide the column that .Net creates for that button, I had to use some custom CSS. Here are the final code snippets:
JS:
function ShowPopUp(ix) {
$(function () {
var message = "Are you sure you want to Remove Data?";
var mydiv = $('#dialog');
mydiv.html(message);
mydiv.dialog(
{
//autoOpen: false,
title: "Data Removal Confirmation",
modal: true,
width: '30 %',
position: { my: 'top', at: 'top+150' },
buttons: {
Yes: function () {
// first, close the dialog
$('#dialog').dialog('close');
btn = $("[id$=btnRemove]")[ix.toString()];
btn.click();
},
No: function () {
$('#dialog').dialog('close');
}
},
});
});
}
Item Templates for the buttons:
<asp:TemplateField ControlStyle-CssClass="visiblyHidden" FooterStyle-CssClass="visiblyHidden" HeaderStyle-CssClass="visiblyHidden" ItemStyle-CssClass="visiblyHidden" HeaderText="">
<ItemTemplate>
<asp:Button
ID="btnRemove"
runat="server"
Text='<%# ((GridViewRow) Container).RowIndex + "" %>'
CssClass="inherited, RemoveData"
CommandName="RemoveData"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reject" FooterStyle-CssClass="rejectHideLeftBorder" HeaderStyle-CssClass="rejectHideLeftBorder" ItemStyle-CssClass="rejectHideLeftBorder">
<ItemTemplate>
<asp:Button
ID="btnRemove2"
runat="server"
Text="Remove Data"
ClientIDMode="Static"
Style="white-space: normal;"
OnClientClick='<%# "ShowPopUp(" + ((GridViewRow) Container).RowIndex + ");return false;" %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
CSS:
.visiblyHidden {
width: 0 !important;
padding: 0 !important;
border: 0 !important;
}
.rejectHideLeftBorder {
border-left: 0 !important;
}

How to get and set value from ASPxSpinEdit during LostFocus event.

I have a ASPxSpinEdit that, onblur I would like to truncate any decimals entered. The following code has two issues. I am able to get the value from the box by using the s.ParseValue() method but cannot seem to reassign it after I do any math to the value. The other issue I am having is I cannot seem to leave the box. After the event fires, the cursor is placed back in the box and will not leave. My code is below. Thank you.
<dx:GridViewDataTextColumn FieldName="InventoryBank" Caption="InventoryBank" Width="100px">
<EditItemTemplate>
<dx:ASPxSpinEdit runat="server" NumberType="Float" DecimalPlaces="1" AllowNull="true" AllowMouseWheel="true" AllowUserInput="true" MinValue="-999999999" ID="lblInventoryBank" Value='<%# Bind("InventoryBank") %>' Width="100px" Increment="1" MaxValue="999999999">
<ClientSideEvents LostFocus="function(s, e) {
s.ParseValue();
var truncatedValue = s.GetNumber();
truncateValue = (truncateValue * 100) / 100;
}">
</ClientSideEvents>
</dx:ASPxSpinEdit>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
So I suppose I should have gone with my gut here and just circumvented DevExpress altogether. The blow code calls a regular javascript function and the solution from there is rather easy.
<dx:GridViewDataTextColumn FieldName="InventoryBank" Caption="InventoryBank" Width="100px">
<EditItemTemplate>
<dx:ASPxSpinEdit runat="server" NumberType="Float" DecimalPlaces="1" AllowNull="true" AllowMouseWheel="true" AllowUserInput="true" MinValue="-999999999" ID="lblInventoryBank" Value='<%# Bind("InventoryBank") %>' Width="100px" Increment="1" MaxValue="999999999">
<ClientSideEvents LostFocus="fnTruncateInt" />
</dx:ASPxSpinEdit>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
And below is the javascript at the top of my page.
function fnTruncateInt(s, e) {
s.SetValue(Math.floor(s.GetValue()));
}

Click event is not working in grid view in asp.net

I have one templete field inside grid view, code is written as below :
<asp:TemplateField HeaderStyle-Width="40px" HeaderStyle-Font-Underline="false" ItemStyle-HorizontalAlign="Center" HeaderText="" >
<ItemTemplate>
<a href="javascript:fillBankDetails(<%# CreateBankDetailsArray(DataBinder.Eval(Container, "DataItem")) %>);window.close();" >Select</a>
</ItemTemplate>
</asp:TemplateField>
and javascript function is written as below
function fillBankDetails(bankDetails) {
alert('Hello');
isSelected = true;
var a = JSON.parse(bankDetails);
window.returnValue = a[0];
}
When I click on select, click event is not firing. Did I have done any mistake. Please help in this.
Thanks in advance.
Try this code
<a href="javascript:fillBankDetails(<%# CreateBankDetailsArray(Eval("DataItem")) %>);window.close();" >Select</a>

How to pass id of a control in GridView to Jquery?

SCRIPT
<script type="text/javascript">
$(function () {
$(".ttip").hide();
$(".txttwo").keyup(
function () {
var one = $(this).val();
$(".ttip").fadeIn().text(one);
});
$(".txttwo").blur(
function () {
var one = $(this).val();
$(".ttip").hide();
});
});
</script>
CODE:
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p class="ttip bubble" class="bubble"></p>
<asp:TextBox ID="abc" class="txttwo tipin" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
FIDDLE
http://jsfiddle.net/w96LX/7/
Also it would be just great if someone can tell me how can I set the width of bubble such that it expands according to the length of text.
I get tooltip for all the textboxes because I have used class. I need to show tooltip just for the one at a time.
Just use $(this).attr("id") to get the ID of an element. Also, apped display:inline-block; width: auto; to make the bubble as big as the content: http://jsfiddle.net/w96LX/26/
Update:
I did not see an ID in your HTML, just the server side code. You will need to append the ID to a HTML element to receive it. Or you generate inline javascript, that is calling a method to set the ID.

Categories