Display image instead of URL - image

I have developed a ASP.NET MVC application with signalr to display the records on the page.
My table has five columns (jobid [int], name[varchar], lastexecutiondate[datetime],status[int],imageurl[string])
Here is my markup from view page:
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th><th>Image URL</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td>' + data[i].imageurl + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px">
</table>
</div>
</body>
And below is my code to get the data from database
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = x.GetString(4)
}).ToList();
I want to display the image instead of the URL.

You should just need to create an image tag in your JavaScript table row function:
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + data[i].imageurl + '"/></td></tr>');
}
I can think of a couple of ways to address your comment below. In code, create a helper function to do this for you:
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = GetImageUrl(x.GetString(3))
}).ToList();
private string GetImageUrl(int status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}
I don't know your code that well, so this assumes that your select is not being cast to a SQL statement (it doesn't appear that it is).
To do the same thing client side, you would implement the GetImageUrl function as a JavaScript function and to the same type of thing.
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + GetImageUrl(data[i].Status) + '"/></td></tr>');
}
function GetImageUrl(status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}

Related

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

How to convert HTML(JSON, Ajax ) into C# WinForm?

I'd like to convert following HTML(json, ajax) Code in C# Winform application.
I'll try it by using JSON.Net, but I'm not familiar with C# WinForm.
I want to binding ajax result value after the user click a button.
How do I this??
html code following that :
Thank you.
// format string
function J2String(object) {
var results = [];
for (var property in object) {
var value = object[property];
if (value != null){
results.push(property.toString() + ': ' + value );
}
}
return '{' + results.join(', ') + '}';
}
// format ajax result data
formatstring = function (text) {
if (arguments.length <= 1) return text;
for (var i = 0; i <= arguments.length - 2; i++) {
text = text.replace(new RegExp("\\{" + i + "\\}", "gi"),
arguments[i + 1]);
}
return text;
}
// return data [ GET method ]
function GetAjaxData(){
RcvData.value = "";
$.ajax({
url:"http://127.0.0.1",
type:"GET",
data: { "REQ": formatstring ("AA^^1000^^^^23^1234567^W1234567890^^00000081") },
dataType: "jsonp",
jsonp: "callback",
success: function(data){
RcvData.value = J2String(data);
}
});
}
<body>
Value : <input type="text" style="width:80%" id="RcvData"><br/>
<form name="tform" method="post">
<input type="button" value="Send" onClick="GetAjaxData()" >
</body>
[ .net framework 4.5 ]
~~~ using ~~ ;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
private async void btnTest_Click(object sender, EventArgs e){
string reqData = "AA^^1000^^^^23^1234567^W1234567890^^00000081";
textBox1.Text = await GetAjaxData(reqData);
}
private async Task<string> GetAjaxData(string reqData){
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost/?callback=jsonp123456&REQ=" + reqData );
response.EnsureSuccessStatusCode();
byte[] buf = await response.Content.ReadAsByteArrayAsync();
Encoding myEncoding = Encoding.GetEncoding("utf-8");
string data = myEncoding.GetString(buf, 0, buf.Length - 1);
dynamic obj = JsonConvert.DeserializeObject(data );
string _parseData = obj.Code
+ "^" + obj.Name
+ "^" + obj.RespCode
+ "^" + obj.Remark;
var result = await Task.FromResult<string>(_parseData);
return result;
}

Google Map doesn't appear on load

I am developing an app where I use 2 API's a.k.a Instagram API and Google Map API. Using AJAX, I get the first set of Images filtered by a tag name. In the 1st set we receive 20 images. Among the received images, the images that have the latitude and longitude info (geotagged images) are displayed on the map.
Now the first time when my page loads, I cannot see the map. But when I press the load more button to get the next set of images, the Map works fine showing my previous images too.
Here is the code for what happens on page load:
$( window ).load(function() {
$.ajax({
type: "GET",
url: "https://api.instagram.com/v1/tags/nyc/media/recent?client_id=02e****",
dataType:'JSONP',
success: function(result) {
onAction(result, 2, tag);
instaMap(result, 2, from);
}
});
});
These are the functions being called:
/**
* [initialize description]
* Initialize the map with markers showing all photos that are geotagged.
*/
var initialize = function(markers) {
var bounds = new google.maps.LatLngBounds(),
mapOptions = {
scrollwheel: false,
mapTypeId: 'roadmap',
center: new google.maps.LatLng(22.50, 6.50),
minZoom: 2
},
gmarkers = [],
map,
positions,
markCluster;
markers = remDuplicate(markers);
// Info Window Content
var infoWindowContent = [];
for (var j = 0; j < markers.length; j++ ) {
var content = [
'<div class="info_content">' +
'<h3>' + markers[j][2] + '</h3>' +
'<a href="' + markers[j][3] + '" target="_blank">' +
'<img src="' + markers[j][4] + '" style="z-index:99999">' + '</a>' +
'</div>'
];
infoWindowContent.push(content);
}
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Display multiple markers on a map
var oms = new OverlappingMarkerSpiderfier(map);
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
positions = new google.maps.LatLng(markers[i][0], markers[i][1]);
marker = new google.maps.Marker({
position: positions,
map: map,
animation:google.maps.Animation.BOUNCE,
title: markers[i][2]
});
oms.addMarker(marker);
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.close();
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
};
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addListener(map, 'click', function() {
infoWindow.setMap(null);
});
markCluster = new MarkerClusterer(map, gmarkers);
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
map.setZoom(2);
google.maps.event.removeListener(boundsListener);
});
};
/**
* [onAction]
* OnAction() function helps in loading non-geotagged pics.
*
* #param {[type]} result [Result retruned from the Instagram API in json format]
* #param {[type]} likey [hearts the user has entered as per which the posts will be filtered]
*/
var onAction = function (result, likey, tag) {
$('.load-pics').remove();
if (result.pagination.next_url) {
paginate = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations === null) {
output = '<li class="img-wrap">' + '<div class="main-img">' +
'<a href="' + link + '" target="_blank">' +
'<img src="' + imgUrl + '" ><span class="hover-lay"></span></a>' +'<p>' +
'<span class="heart"></span><span class="likes-no">' + liked + '</span>' +
'<span class="comment-box"></span><span class="comment-no">' +
val.comments.count + '</span> ' + '</p>' + '</div>' +
'<div class="img-bottom-part">'+ '' + '<div class="headin-hastag">' +
'by ' + '<h2>Sebastien Dekoninck</h2>#hello <span>#kanye</span> #helloagain #tagsgohere</div>'
+'</div></li>';
$('#instafeed').append(output);
}
}
});
}
});
if ($('#instafeed').children().length === 0) {
alert('There are no pics with ' + likey + ' likes or #' + tag + ' was not found.');
} else {
// $('.not-geo').remove();
// $('#instafeed').before('<button class="not-geo">Click To See Images That Are Not Geotagged <img src="assets/imgs/down.png" ></button>');
}
$('#instafeed').append('<div class="load-pics"><button id="show-more">Show more <span></span></button> </div>');
};
/**
* [instaMap]
* instaMap() will be the function which will deal with all map based functionalities.
*/
var instaMap = function(result, likey, from) {
$('.load-mark').remove();
if (result.pagination.next_url) {
pagiMap = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations && locations.latitude !== null) {
tempArr = [
locations.latitude,
locations.longitude,
val.user.username,
val.link,
val.images.low_resolution.url
];
mark.push(tempArr);
}
}
});
}
});
if (mark.length) {
initialize(mark);
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
} else {
alert('No geotagged pics found in the retrieved set. Click see more');
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
}
};
I have created a See More button to retrieve the next set of images and load those on the Map. When clicking see more, everything seems to work fine. Not sure why it's happening so. Console.log does not show any error. Also, all the values I feed does flow appropriately. I even tried clearing cache. Not sure, why it's happening.
If instaMap is the function which is going to handle all your map based functionality, it has to be the one that loads map in your $( window ).load function ();
Otherwise, if you want Google maps to load on initial window load you need to put below in there:
google.maps.event.addDomListener(window, 'load', initialize);

AJAX Jquery: execution order of events

I have a webpage with different elements (a list of links and two select boxes) connected between them. Clicking on them may affect one of the other element and all of their values contribuite to update a value to show on the page.
So, the code is this:
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change();
console.log('second' + someVar);
});
function my_change() {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
When I load the page the my_change function is called. It does some stuff and then triggers a change event on a select-box. I need to update a value using what's inside this select box and only then let the execution to proceed. So what I need this code to do would be to print 'first', and then 'second' with the value of the variable. What actually happen is that it prints 'second' 'first'.
I think it's because I'm doing asynchronous calls. What can I do?
There's several ways to do this.
You could use jQuery $.when and call the console.log after the ajax response finishes.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
$.when( my_change() ).then(function(){
console.log('second' + someVar);
});
});
function my_change() {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
Or you could add a callback argument to the my_change(callback) function.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change(function(){ console.log('second' + someVar) } );
});
function my_change(callback) {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
if( typeof callback !== 'undefined' && typeof callback === 'function' )
callback();
$("select#options").html(options.join('')).trigger('change');
})
};
};
The 'second' console.log() is being called first since the asynchronous $.getJSON() call waits for the response from the server before firing its callback function. You could save the jqXHR object to a variable and then use that to run your 'second' consone.log() with $.when():
$(function() {
var someVar = '';
$("#size").on('change', function() {//on() is the same as bind() here
someVar = $(this).val();
console.log('first');
});
//save the jQuery XHR object from your $.getJSON request
var jqXHR = my_change();
//when the above jQuery XHR object resolves, it will fire the second console.log
$.when(jqXHR).then(function () {
console.log('second' + someVar);
});
});
function my_change() {
//here we return the jQuery XHR object for the $.getJSON request so we can run code once it resolves
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("#size").trigger('change');
$("#options").html(options.join('')).trigger('change');
})
};
Here is documentation for $.when(): http://api.jquery.com/jquery.when
A quick side-note: it is generally slower to add a tag-type to a selector, especially when you are selecting IDs as that is already a very fast method of selecting elements.
Any code that relies on the response of the getJSON must be placed in, or called from, the getJSON callback.
That's what a callback is for.
You should note that your my_change function will not have access to the someVar variable because it is local to the ready() callback.
To remedy this, move the my_change function inside the ready() callback.
Or just pass a function directly to my_change.
my_change(function() {
console.log('second' + someVar);
});
And have the getJSON callback invoke the function.
function my_change( func ) {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
func();
});
}

Dynamic javascript in ASP.Net MVC 3.0+Razor

I have a javascript that must generate in runtime.The text of script is generate in controller class :
private string mapString
{
get
{
Locations loc = new Locations();
string appPath = Request.ApplicationPath;
loc.ReadXml(Path.Combine(Request.MapPath(appPath) + "\\App_Data", "Locations.xml"));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < loc.Specfications.Count; i++)
{
sb.Append("var myLatLng" + i.ToString() + "= new google.maps.LatLng(" + loc.Specfications[i].Y.ToString() + "," +
loc.Specfications[i].X.ToString() + ");");
sb.Append(" var beachMarker" + i.ToString() + " = new google.maps.Marker({position: myLatLng" + i.ToString() + ",map: map,icon: image,title:'" + loc.Specfications[i].Title + "'});");
....
...
...
ViewData["MapString"] = mapString;
When I use it in script tag :
<script type="text/javascript">
function initialize() {
#Server.HtmlDecode(ViewData["MapString"].ToString())
}
</script>
It dosen't return a true text and it retruns something like this:
contentString0 = '<table width="100%" style="font-family: tahoma; text-align: right; font
**update : The site didn't show my question correctly ,I want to show "'<" but it show "'<"
but it must return :
contentString0 ='
you see that it convert "'<" to "'<" .
But when I use : #Server.HtmlDecode(ViewData["MapString"].ToString()) out of script tag ,all things is OK.
You may want to do it this way, which I think is going to be more flexible than generating code in your controller :
Controller action :
public JsonResult GetCoords()
{
// your code here - im putting a generic result you may
// need to put some logic here to retrieve your location / locations
var result = new { lon = "51.0000", lat = "23.0000" };
return Json(result, JsonRequestBehavior.AllowGet);
}
in your view add :
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/YourController/GetCoords', function (jsonData) {
var lon = jsonData.lon;
var lat = jsonData.lat;
yourGoogleMapFunction(lon, lat);
});
});
</script>

Resources