I'm trying to display a context menu for each row in the gridview.
The context menu needs to pass specific variables for each row, for example, a unique userid.
I would like the ul to only be on the page once I have passed variables or something
<ul id="myMenu" class="contextMenu">
<script src="scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="scripts/jquery.contextMenu.js" type="text/javascript"></script>
<link href="jquery.contextMenu.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready( function() {
// Show menu when #myDiv is clicked
$("img").contextMenu({
menu: 'myMenu'
},
function(action, el, pos) {
alert(
'Action: ' + action + '\n\n' +
'Element ID: ' + $(el).attr('id') + '\n\n' +
'X: ' + pos.x + ' Y: ' + pos.y + ' (relative to element)\n\n' +
'X: ' + pos.docX + ' Y: ' + pos.docY+ ' (relative to document)'
);
});
});
</script>
<form id="form1" runat="server">
<div>
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgPop" runat="server" ImageUrl="~/images/pop.gif" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="First Name" DataField ="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField ="LastName" />
</Columns>
</asp:GridView>
<ul id="myMenu" class="contextMenu">
<li class="edit">Edit</li>
<li class="cut separator">Cut</li>
<li class="copy">Copy</li>
<li class="paste">Paste</li>
<li class="delete">Delete</li>
<li class="quit separator">Quit</li>
</ul>
</div>
Of more use would be the actual HTML output from the page, as opposed to the ASPX, as it seems your question lies mainly within jQuery.
I'm still not entirely sure when your context menu created, but this would be how you add it the DOM dynamically:
$("<ul id='myMenu' class='contextMenu'>").appendTo(selector);
//...selector selects some item in the DOM.
I'm not seeing #MyDiv anywhere in the HTML, so maybe you need:
<div id='MyDiv'>
To bind to a click event:
$('#MyDiv').click(function(){
//do something
});
Can you maybe try and be a bit clearer on what you want - even add some pseudocode to your script sample so we can fill in the gaps, for example, where you envisage userid being used.
Related
I have 6 dropdowns in a aspx page. I need to populate the dropdown only when its clicked.
Initially I populated all 6 ddl in page load but there was a huge delay in loading the page so I got this option to populate the ddl only when its clicked. I couldn't find the right answer yet, tried with diff sol and query.
And i couldn't find any 'Onclick','Onmousedown','Onkeypress' in ddl.
I even tried one option shared in stackoverflow by an user.
pls find the below code and help to solve the issue.
<td class="style10" >
<asp:DropDownList runat="server" ID="ddlGM" Width="150px" AutoPostBack="True" onclick="javascript:clickHiddenButton();" onselectedindexchanged="ddlGM_SelectedIndexChanged" style="height: 22px" >
<asp:ListItem Value=0 Text="All"></asp:ListItem></asp:DropDownList><div style="display: none;">
<asp:Button ID="btnHidden" runat="server" Text="Button" />
</div></td>
<script type="text/javascript">
function clickHiddenButton() {
var btn = document.getElementById('btnHidden');
var ddl = document.getElementById('ddlGM');
if (ddl.length == 1) {
btn.click();
}
}
</script>
protected void btnHidden_Click(object sender, EventArgs e)
{
DataView dvfilters = (DataView)(Cache["FiltersData"]);
dtt = dvfilters.ToTable();
ddlGM.DataSource = dtt;
ddlGM.DataValueField = "GlobalMarket";
ddlGM.DataBind();
RemoveDuplicateItems(ddlGM);
SortDDL(ref ddlGM);
//ddlGM.Items.Insert(0, "All");
}
You can use .focus function for any element. focus function is called when the particular function get clicked or getting focus by anyway. I am putting sample code for you. You can change this code as your need.
<script>
var bDataLoded = false;
$(document).ready(function () {
var ddVal = '';
$('#ddlGM').focus(function () {
if (!bDataLoded) {
alert("hi");
$('#ddlGM').append('<option value=' + 1 + '> + Test 1 + </option>');
$('#ddlGM').append('<option value=' + 2 + '> + Test 2 + </option>');
$('#ddlGM').append('<option value=' + 3 + '> + Test 3 + </option>');
$('#ddlGM').append('<option value=' + 4 + '> + Test 4 + </option>');
bDataLoded = true;
}
$('#ddlGM').blur();
})
});
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="ddlGM" Width="150px" AutoPostBack="True" style="height: 22px" >
</asp:DropDownList>
</div>
</form>
Hope this will solve your problem.
I have gridview showing columns BusRoute,BusNo and Action.Where action contains the linkbuttons to display another gridview.I want to display it in jquery dialog.My codes are.
ASPX Code:
First Gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClientClick="showDialog();">Shipment Status</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
Second Gridview:
<div class="gridview_stop" id="popup">
<asp:GridView ID="Stops" runat="server" AutoGenerateColumns="False" CellPadding="6" Width="190px">
<Columns>
<asp:BoundField HeaderText="Bus Stop" DataField="StopName" HeaderStyle-BackColor="#006B89">
<HeaderStyle BackColor="#006B89" Font-Size="18px" Font-Bold="false"></HeaderStyle>
<ItemStyle BackColor="#E0E0E0" HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
Code Behind File:
protected void search_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("spGetRoutes", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BusStop1", Source.Text);
cmd.Parameters.AddWithValue("#BusStop2", Destination.Text);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
adapter.Dispose();
cmd.Dispose();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Route.DataSource = ds.Tables[0];
Route.DataBind();
Stops.DataSource = null;
Stops.DataBind();
Lblmsg.Text = "";
}
else
Lblmsg.Text = "No Direct Bus Between These Stop";
Lblmsg.ForeColor = Color.WhiteSmoke;
Route.Dispose();
Route.DataBind();
Stops.Dispose();
Stops.DataBind();
}
protected void Route_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string Name = Route.SelectedRow.Cells[0].Text;
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
string connetionString = "Data Source=.;Initial Catalog=BusService;uid=sa;Password=Murli#925";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand cmd = new SqlCommand("spGetStops", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
int BusNo= Convert.ToInt32(Name);
cmd.Parameters.AddWithValue("#BusNo",BusNo);
adapter1.SelectCommand = cmd;
adapter1.Fill(ds1);
adapter1.Dispose();
cmd.Dispose();
connection.Close();
Stops.DataSource = ds1.Tables[0];
Stops.DataBind();
}
Jquery Function:
<script type="text/javascript">
$("#lnkbtn").live("click",
function showDialog() {
$("#popup").dialog({
show: { effect: "fold", duration: 4000 },
hide: { effect: "fold", duration: 4000 },
});
return false;
});
$(document).click(function (event) {
if (!$(event.target).closest('#popup').length) {
if ($('#popup').is(":visible")) {
$('#popup').dialog('close');
}
}
})
</script>
Thanks & Regards.
Take a look at your rendered html when you run the page. Unless you set ClientIDMode to Static I doubt that your button ID's are $("#lnkbtn") but more like $("#gvWhatever_lnkbtn_0")
Set OnClientClick="showDialog();" or $("#lnkbtn").live("click", function showDialog(){...}) no need to do both.
Using a Server Control button to activate a popup usually doesn't work. Especially if GridView Row Selection is enabled. I can't tell if your first GridView has that feature enabled as I only see a portion of the listing. But what tends to happen is you trigger a postback while trying to display the popup so you never see the popup.
Also your second popup contains a gridview, which requires a databind. so you need to make sure the gridview is populated with the data before activating the popup
Two methods for showing a popup using jquery from within a Gridview:
A portion of a GridView markup with 2 TemplateField's
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div>
<div class="rs-icon rs-icon-info tooltip-marker" role="button">
</div>
<div id="ContactInfo" style="display:none;">
<table id="tblContactDetail" class="ContactDetail Note">
<tr>
<td style="width: 80px">Name</td>
<td style="width: 100%">
<asp:Literal ID="Literal1" runat="server"
Text='<%# Eval("expert_name") %>' />
</td>
</tr>
.
.
.
</table>
</div>
</div>
<ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CV">
<ItemTemplate>
<div id="divButtonViewCV" runat="server"
class="rs-icon rs-icon-cv" role="button"
onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>' >
</div>
</ItemTemplate>
</asp:TemplateField>
In the above markup I'm setting up for two styles of "popup". The first Template uses jQueryUI ToolTip widget which is activated on mouseover/out. This is nice because it doesn't require a click which means no worries about a postback mucking up the works. The interesting thing here is that I'm using a div as button.
How it works: The div with the .tooptip-marker class is set up to activate a jqueryui tooltip which will display the contents of <div id="ContentInfo"> by grabbing the inner html of the sibling div of the activating button. Note that this div is styled as display:none; so that the content is available for the tooltip but hidden so the main GridView displays as normal.
For brevity, I included only a portion of the content of <div id="ContentInfo">. But It can contain anything really. In my code it's a simple <table> containing contact information fields (using bound <asp:Literal> controls) that are part of the primary GridView data source.
But this could just have easily been an embedded GridView with it's own data source that is bound in the OnRowDatabound event of the primary GridView.
The following jquery sets up the widget. See jQueryUI ToolTip widget for more complete documentation
$( function() {
$( document ).tooltip( {
items: ".tooltip-marker",
content: function() {
return $( this ).next().html();
},
position: {
my: "left top",
at: "right+5 top-5"
}
} )
} );
The second Template field is used to activate a popup. This is where you have to be careful about postbacks. Again I use a <div> styled as an icon and treated as a simple button because I've added onclick.
Clicking this button displays a popup so you can view a persons CV in PDF format. The PDF is stored in our database as a varbinary. Here I use another jquery addon, (colorbox), to display the PDF as a popup over the page.
In the ViewPDF() function below note that we prevent the "bubbling up" of the click event to the GridView by setting cancelBubble = true (for older IE) or a call to stopPropagation() (all other browsers).
In this code, colorbox sets up an iframe and passes the href parameter to its src attribute. I'm making a call to an .ashx page which is an asp Generic Handler which allows us to serve up other type of content without standard web page overhead. This could just as easily been configured to accept a standalone .aspx page where you could maybe place your secondary grid.
// This plain object is used by the call to colorbox(), please
// refer to colorbox documentation for details.
var colorboxDataExpertCV = {
height: "85%",
width: 900,
opacity: .30,
fixed: true,
iframe: true,
returnFocus: false,
href: ''
}
// ========================================================
// In the Template above, the onclick code:
// onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>'
//
// Renders to:
// onclick="ViewPDF(12345)"
//
// PdfHandlerExpertsCV.ashx is an GenericHandler that retrieves
// the CV from our database and writes the byte array to the
// colorbox iframe as an "application/pdf" content type which
// triggers native browser pdf management either by internal
// viewer or installed PDF plugin
// ========================================================
function ViewPDF( p ) {
if ( event.stopPropagation )
event.stopPropagation();
else
event.cancelBubble = true;
if ( p && p > 0 ) {
colorboxDataExpertCV.href = "/PdfHandlerExpertsCV.ashx?cvid=" + p;
$.colorbox( colorboxDataExpertCV );
}
return false;
}
Addendum
Let me make it more clear, I need to bind the data in 2nd Gridview and
display this Gridview2 in Jquery dialog .This data will be binded and
displayed in dialog from on the click event of linkbutton inside
Gridview1
As I said above, you cannot bind a GridView (server side event) and then popup a jquery ui dialog (client side event) without introducing much more complexity. You have to make sure all the data you need for the popup is available by the time you're ready to hit the button that opens the dialog.
The simplest way to accomplish this is to embed GridView2 within GridView1 and take care of the binding all at once. It's not pretty or efficient and, depending on the number of items shown in each, can slow down the page. But if you have only a few lines for each it should be acceptable.
Embed GridView2 and DataSource2 in the <ItemTemplate> of a <TemplateField> of GridView1.
Bind GridView2 in the RowDataBound event of Gridview1 using an appropriate row field or datakey field from GridView1 and then calling GridView2.DataBind().
Add a element to the same TemplateField
Refer to the jquery dialog modal form example which shows how to trigger a dialog from a button click. In your case substitute the second GridView for the Form in the example.
IMPORTANT be mindful that gridview row item id's get "mangled" so you should not use id's in the jquery calls but use jquery selectors that are based on element name plus class markers, ie: $("button.marker") for a button defined like this: <button class="marker">.
Addendum: 2015-Jun-24
CSS (<head> tag)
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui.css" />
<script type="text/javascript" src="Scripts/jquery-2.1.4.min.js"> </script>
<script type="text/javascript" src="Scripts/jquery-ui-1.11.4.min.js"> </script>
<style>
.btn_styling {
text-align: center;
width: 32px;
margin: 2px;
cursor: pointer;
border: 1px solid gray;
border-radius: 3px;
/* add a background image to the div
to make the div look like a button */
/* background-image: url('...') */
}
.ui-dialog-titlebar-close {
display: none;
}
</style>
HTML (.aspx)
<form id="form1" runat="server">
<div style="width: 400px;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="user_id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an <img> element...anything really">X</div>
<div style="display: none;">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />
<asp:BoundField DataField="add_edit_date" HeaderText="Date Added" SortExpression="add_edit_date" DataFormatString='{0:dd-MMMM, yyyy}'/>
<asp:BoundField DataField="add_edit_by" HeaderText="Added By" SortExpression="add_edit_by" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT email, add_edit_date, add_edit_by FROM tbl_users WHERE (user_id = #user_id)">
<SelectParameters>
<asp:Parameter Name="user_id" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT top 10 user_id, user_name from tbl_users">
</asp:SqlDataSource>
</div>
<div id="dialogContainer">
</div>
</form>
Code Behind (VB):
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv2 As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
Dim sds As SqlDataSource = DirectCast(e.Row.FindControl("SqlDataSource2"), SqlDataSource)
sds.SelectParameters("user_id").DefaultValue = GridView1.DataKeys(e.Row.RowIndex).Value
gv2.DataBind()
End If
End Sub
jQuery to implement Dialog:
<script type="text/javascript">
var dialogOptions = {
autoOpen: false,
appendTo: "#dialogContainer",
modal: true,
height: "auto",
width: "auto",
title: "Dialog Title",
closeOnEscape: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
};
$( function() {
$( ".dialog-marker" ).on( "click", function() {
var d = $( this ).next( "div" ).first().dialog( dialogOptions );
d.dialog( "open" );
} );
} );
</script>
I am building a quick web app to display locations markers on google maps from sql server database. On my, aspx page I have a repeater control that displays the lat long of the locations in the database.
<asp:Repeater runat="server" ID="rptMarkers">
<ItemTemplate>
title: '<%# Eval("LocationName")%>'<br />
lat : '<%# Eval("Latitude") %>' <br />
long : '<%# Eval("Longitude") %>
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
Now what I need guidance with is , how to pass the values returned in both
'<%# Eval("Latitude")%>' and <%# Eval("Latitude") %> into a javascript array. So that I can use the values in the javascript array to build map markers. I know how to display the markers in google map with when I get the javascript lat long arrays. Only using the values from the repeater to build the javascript array is my challenge
I'm Just modifying your code .
take data in label control , like this
long : <asp:Label ID="lblLongitude" runat="server" Text='<%#Eval("Longitude") %>'></asp:Label><br />
lat : <asp:Label ID="lblLatitude" runat="server" Text='<%#Eval("Latitude") %>'></asp:Label><br />
then get all data in Js
$(document).ready(function () {
var Longitude= [];
var Latitude= [];
$('*[id^=rptMarkers_lblLongitude]').each(function () {
Longitude.push($(this).html());
});
$('*[id^=rptMarkers_lblLatitude]').each(function () {
Latitude.push($(this).html());
});
});
How are you binding data to the repeater? I guess you have some kind of data source. Try this:
<script type="text\javascript">
var location = [];
<% foreach(var elm in dataSource) %>
<%{ Response.Write("location.push({'lat': " + elm.Latitude + " , 'long': " + elm.Longitude + "});"); }%>
If you have to use a repeater, change the code like this:
<script type="text\javascript">
var location = [];
</script>
<asp:Repeater runat="server" ID="rptMarkers">
<ItemTemplate>
title: '<%# Eval("LocationName")%>'<br />
lat : '<%# Eval("Latitude") %>' <br />
long : '<%# Eval("Longitude") %>'
<script type="text\javascript">
location.push({'lat': '<%# Eval("Latitude") %>', 'long': '<%# Eval("Longitude") %>'});
</script>
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
Don't use a repeater. Create an anonymous array of values then use the JavaScriptSerializer to create the array.
say your dataset is called data & contains objects with properties as you've used above.
var j = new JavaScriptSeializer()
var result = j.Serialize(data.Select(i=>new { title=i.LocationName, lat=i.Latitude, lon=i.Longitude }));
Then in your JavaScript code block
var location = <%=result%>;
Even better would be to use the JSON.Net serializer (site, nuget) but that might be overkill for one small function
Does anyone know how to use an sap ui5 control with the asp:repeater control. Everytime I try to put a button, it only shows up in the first iteration of the repeater. And not in the rest of the iterations
<asp:Repeater ID="NewsFeedID" runat="server" >
<ItemTemplate>
<script type="text/javascript">
var buttonlink = CommentsPage + "?news=" + '<%# Eval("NewsFeedID") %>';
var AddComment = new sap.ui.commons.Button({
text: "Add Comment",
icon: AddCommentIcon,
lite: true,
press: function () { window.location = buttonlink; }
}).placeAt("Comments");
</script>
<div id="Comments"></div>
</td>
</tr>
When I use this code it only shows up for the first iteration of the asp:repeater but I want it to show up for all iterations. Does it have something to do with the div id=Comments? Need help please
Your Repeater creates multiple <div> elements with the same id, which causes conflicts.
One way to fix the problem is to add a runat="server" attribute to the <div>, making it a server-side control so that ASP.NET generates a unique ID for each instance:
<div runat="server" id="Comments"></div>
Then pass the dynamically generated ID to the placeAt function:
}).placeAt("<%# Container.FindControl("Comments").ClientID %>");
You can rename every instance with the index of repeater item:
<script type="text/javascript">
var buttonlink = CommentsPage + "?news=" + '<%# Eval("NewsFeedID") %>';
var AddComment = new sap.ui.commons.Button({
text: "Add Comment",
icon: AddCommentIcon,
lite: true,
press: function () { window.location = buttonlink; }
}).placeAt("<%# "Comments"+ Container.ItemIndex+1 %>");
</script>
<div id="<%# "Comments"+ Container.ItemIndex+1 %>"></div>
Trying to reload an iframe after C# has modified its attributes. Here's the page:
<script type="text/javascript">
function reloadFrame(Map) {
document.getElementById(Map).contentDocument.location.reload(true);
}
</script>
<asp:TextBox ID="TextBox1" placeholder="Zip code" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Find locations" onclick="Button1_Click" />
<iframe id="Map" runat="server"></iframe>
And when the button is clicked it runs this:
var zipCode = TextBox1.Text;
Map.Attributes.Add("src", "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode);
browser.Document.InvokeScript("reloadFrame", new[] { "Map" });
However the line to reload the iframe doesn't work. Any ideas?
How about setting the src for the iFrame via inline code?
<iframe id="Map" runat="server" src='<%= (TextBox1.Text == "" ? "" : "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode) %>'></iframe>