Pass asp.net repeater items to javascript array - c#

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

Related

Reloading iframe in ASP.NET site from C# code

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>

How to display the property of an image displayed on the asp page by selecting relevant radio button

Actually I'm working on an ascx file which displays images in a specified folder.
The task is to place a radio button for each image, and when a radio-button is selected, the details (like the image's name) of the appropriate image should be shown in a pop-up box.
Please, help me finish the task!
<asp:DataList ID="dlAssignftp" Visible="false" runat="server" RepeatColumns="5" RepeatDirection="Vertical"
HorizontalAlign="left" CellPadding="1" CellSpacing="1" Width="100%">
<ItemTemplate>
<ul class="gallery clearfix slideshow">
<li>
<a href='<%# DataBinder.Eval (Container.DataItem, "Image Path") %>' rel="prettyPhoto[pp_gal]">
<asp:Image ImageUrl='<%# DataBinder.Eval (Container.DataItem, "Image Path") %>' ID="imgftp"
runat="server" Height="100px" Width="100px" Visible="true" />
</a>
</li>
<asp:RadioButton ID="rbtn_ftpimg" runat="server" Text="Select" GroupName="rbtn_ftpimg_grp" Checked="false" TextAlign="Right" OnCheckedChanged="rbtn_ftpimg_Changed" AutoPostBack="true" />
</ul>
<%--</a>--%>
</ItemTemplate>
</asp:DataList>
Depending on what properties you are looking for exactly you could do something like this:
Image img = Image.FromFile(<path to image on server>);
//return data to web: img.Width, img.Height etc.
Additionally I think you can do something like this:
PropertyItem[] itms = img.PropertyItems;
foreach(PropertyItem item in itms)
{
//iterate through items and do work
}
Does that help?
--- Edit ---
The above code should give you the details you are looking for but as far as how you go about displaying them is entirely up to you. What I would probably do would be something similar to the following:
<script language="javascript">
function GetImageDetails(id)
{
$.ajax({
url: '/Images/GetImageDetails',
type: "POST",
data: { imageId: id },
dataType: 'json',
success: function (data) {
var content;
content = data[0].Width;
content += "<br>";
content += data[0].Height;
content += "<br>";
//etc
alert(content);
}
});
}
</script>
<input type=radio onClick="GetImageDetails(1);">
Then on the server side you might have a webservice that looks like this:
public JsonResult GetImageDetails(int ID)
{
var img = Image.FromFile(<path to image on server>);
return Json(new { width = img.Width, height = img.Height });
}
You could modify this any number of ways to suit your needs. For example you will notice that I pass an id parameter into the Web Service method (I don't do anything with it in the example however) which I would use to pull the physical location of the image out of the database. Alternatively you could just pass in the path to the image to avoid the round trip to the database server. Again how you go about doing this is really up to you.
One final point the above web service method is akin to what you would find in an MVC 3/4 environment. If you are not running MVC you could do something like this instead:
public string GetImageDetails(int ID)
{
var img = Image.FromFile(<path to image on server>);
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { width = img.Width, height = img.Height });
}
Hope this helps.

How to pass control.ClientId to an OnClick function in ASP.NET?

I'm trying to turn on/off various RequiredFieldValidator controls when checkboxes are checked/unchecked, based on this question. But rather than having a separate js function for each checkbox I want to pass in the ClientID of the input to validate, something like this (only one INPUT here but you can see once it's working I can add more INPUTs without more js):
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%= rfvSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
Currently that scriptlet txtSubject.ClientID isn't evaluated, just output directly. I'm sure this is simple but I just don't know the appropriate syntax.
How about adding it via the codebehind (or a script section):
checkSubjectRequired.Attributes.Add("onclick", "updateValidator(" +
txtSubject.ClientID + ")");
This explaination of ClientID may be helpful.
This is because; ASP.NET parser can not parse server tag "<% = %>" for a server side control (i.e. control made as runat='server').
Use the following:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%#txtSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
You could just do this:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClientClick="updateValidator(this.id);" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>

Write date in asp:TextBox

<asp:TextBox ID="txtDate" runat="server" Value="<%= DateTime.Today.ToShortDateString() %>" />
Value="<%= DateTime.Today.ToShortDateString() %>" does not write date in txt field but whole string. What i am doing wrong?
using JavaScript and jQuery:
var now = new Date();
$('#txtDate').text(now.getDate() + '/' + now.getMonth()+ '/' + now.getYear());
or plain JavaScript:
var now = new Date();
document.getElementById('txtDate').value = now.getDate() + '/' + now.getMonth()+ '/' + now.getYear();
or in markup (using System.Web.UI.WebControls.TextBox.Text property, it has no Value property):
<asp:TextBox ID="txtDate" runat="server" Text="<%# DateTime.Today.ToShortDateString() %>" />
and after that call this.DataBind(); or not for page, but your TextBox's parent control.
See this similar question.
As you've seen, you can't use the <%= %> construct to set a property of a server control.
The usual way to set a property in markup is to use a <%# data-binding expression %>

asp.net gridview jquery contextmenu

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.

Categories

Resources