MVC 4 - 500 error on JSON call - asp.net

I have started using VS2012 (Yes about time). I have a MVC 4 app.
Im making a JSON call to get data from DB to render in html.
But Im getting a 500 Internal Server error I can see in Fiddler.
Im not sure how to debug this because I cant find where to
see the C# exception if that is what the issue is.
So Im calling getRecipe in javascript.
public JsonResult GetRecipe(int rid)
{
var recipe = _rep.GetRecipe(rid);
return Json(recipe, JsonRequestBehavior.AllowGet);
}
My script is
var dataService = new function () {
var serviceBase = '/Recipes/'
getRecipesList = function (callback) {
$.getJSON(serviceBase + 'GetRecipesList', {}, function (data) {
callback(data);
});
};
getRecipe = function (rid, callback) {
$.getJSON(serviceBase + 'GetRecipe', {rid:rid}, function (data) {
callback(data);
});
};
return {
getRecipesList: getRecipesList,
getRecipe: getRecipe
};
} ();
var renderer = new function () {
renderList = function () {
dataService.getRecipesList(renderListDiv);
},
renderListDiv = function (recipes) {
var listDiv = $('#listdiv');
listDiv.html("");
$(recipes).each(function (index) {
var table = '<table>';
table += ('<tr><td><a class="recipeLink" href="#recipeList-' + this.RecipeID + '">' + this.RecipeTitle + '</a></td></tr>');
table += '</table>';
listDiv.append(table);
});
},
selectedRecipe = function (anchor) {
var href = $(this).attr("href");
var rid = href.split("-")[1];
dataService.getRecipe(rid, renderRecipe);
};
renderRecipe = function (recipe) {
var recipeDiv = $('#recipediv');
var html = '<h1>' + recipe.RecipeTitle + ' (' + recipe.RecipeID + ')</h1>';
html += '<h4>Preparation Time: ' + getTimeString(recipe.PrepTime) + '</h4>';
html += '<h4>Cooking Time: ' + getTimeString(recipe.CookTime) + '</h4>';
var count = recipe.Ings.length;
var colmax = Math.ceil(count / 2);
var colleft = 0;
var colright = colmax;
html += '</br><table id="ingredientstable">';
for (colleft = 0; colleft < colmax; colleft++) {
html += '<tr>';
html += '<td>' + recipe.Ingredients[colleft].Units + ' ' + recipe.Ingredients[colleft].Measure + ' ' + recipe.Ingredients[colleft].IngredientName + '</td>';
if(colright < count)
html += '<td>' + recipe.Ingredients[colright].Units + ' ' + recipe.Ingredients[colright].Measure + ' ' + recipe.Ingredients[colright].IngredientName + '</td>';
colright += 1;
html += '</tr>';
}
html += '</table>';
html += '<h4>Method</h4>';
html += '<p>' + recipe.Method + '</p>';
recipeDiv.html(html);
numingredients = 0;
editorForm.loadEditor(recipe);
};
clearRecipe = function () {
$('#recipediv').html("");
};
getTimeString = function (time) {
if (time < 60)
return time + ' min';
return time / 60 + ' hours'
};
changeFont = function () {
$('body').css("font-family", "Comic Sans MS");
};
return {
renderList: renderList,
selectedRecipe: selectedRecipe,
changeFont: changeFont,
clearRecipe: clearRecipe,
};
}();

The browser's developer tools might be a good place to get some additional information. In Chrome you can press F12 to bring up the dev tools window. Click on the network tab and then fire off your ajax call. You will see the failed request highlighted in red. If you click on it you will see the error that has been returned from mvc.
I have provided a screenshot in this question: Ajax call with a 'failed to load resource : the server responded with a status of 500'

Related

Marker change based on text/address input using HERE map

I'm using HERE map plugin and I need to change marker position based on address/text input. I was looking for an examples in internet, but nothing was found.
Is it even possible to do such thing, using this plugin? May be someone can point out, where do I have to look, or may be someone have working example? Any help appreciated.
Something similar is used in "Google Maps"
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
You can refer to the documentation for "Search for a Location based on an Address" can be found at https://developer.here.com/documentation/examples/maps-js/services/geocode-a-location-from-address
The working example is available at https://jsfiddle.net/4Lodwfb3/ - request a location using a free-form text input and display a marker on the map.
function geocode(platform) {
var geocoder = platform.getSearchService(),
geocodingParameters = {
q: '200 S Mathilda Sunnyvale CA'
};
geocoder.geocode(
geocodingParameters,
onSuccess,
onError
);
}
function onSuccess(result) {
var locations = result.items;
addLocationsToMap(locations);
addLocationsToPanel(locations);
}
function onError(error) {
alert('Can\'t reach the remote server');
}
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map,{
center: {lat:37.376, lng:-122.034},
zoom: 15,
pixelRatio: window.devicePixelRatio || 1
});
window.addEventListener('resize', () => map.getViewPort().resize());
var locationsContainer = document.getElementById('panel');
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers);
var bubble;
function openBubble(position, text){
if(!bubble){
bubble = new H.ui.InfoBubble(
position,
{content: text});
ui.addBubble(bubble);
} else {
bubble.setPosition(position);
bubble.setContent(text);
bubble.open();
}
}
function addLocationsToPanel(locations){
var nodeOL = document.createElement('ul'),
i;
nodeOL.style.fontSize = 'small';
nodeOL.style.marginLeft ='5%';
nodeOL.style.marginRight ='5%';
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
var li = document.createElement('li'),
divLabel = document.createElement('div'),
address = location.address,
content = '<strong style="font-size: large;">' + address.label + '</strong></br>';
position = location.position;
content += '<strong>houseNumber:</strong> ' + address.houseNumber + '<br/>';
content += '<strong>street:</strong> ' + address.street + '<br/>';
content += '<strong>district:</strong> ' + address.district + '<br/>';
content += '<strong>city:</strong> ' + address.city + '<br/>';
content += '<strong>postalCode:</strong> ' + address.postalCode + '<br/>';
content += '<strong>county:</strong> ' + address.county + '<br/>';
content += '<strong>country:</strong> ' + address.countryName + '<br/>';
content += '<strong>position:</strong> ' +
Math.abs(position.lat.toFixed(4)) + ((position.lat > 0) ? 'N' : 'S') +
' ' + Math.abs(position.lng.toFixed(4)) + ((position.lng > 0) ? 'E' : 'W') + '<br/>';
divLabel.innerHTML = content;
li.appendChild(divLabel);
nodeOL.appendChild(li);
}
locationsContainer.appendChild(nodeOL);
}
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
marker = new H.map.Marker(location.position);
marker.label = location.address.label;
group.addObject(marker);
}
group.addEventListener('tap', function (evt) {
map.setCenter(evt.target.getGeometry());
openBubble(
evt.target.getGeometry(), evt.target.label);
}, false);
map.addObject(group);
map.setCenter(group.getBoundingBox().getCenter());
}
geocode(platform);

I need to receive fetch post from my wordpress to phonegap using wordpress rest api & json

please i need help concerning phonegap and wordpress rest api.. I am a bit new to phonegap. i want to be able to receive my latest posts using GET etc and likely post from my mobile and also possibly perform other CRUD operation. thanks
I got it done already thanks much. I am posting my code here to help some out there and these community:
// Device Event Listener
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
var portfolioPostsContainer2 = document.getElementById("portfolio-posts-container2");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://mydomain/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
// portfolioPostsBtn.remove();
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
function createHTML(postsData) {
var ourHTMLString = '';
var postid ='';
for (i = 0; i < postsData.length; i++) {
var posturl = postsData[i].link;
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + postsData[i].id+''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + '</td>';
ourHTMLString+= '</tr>';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}

Inserting table into Trirand JQGrid Edit Dialog that was creating with JQuery

I have a JQuery and AJAX function that creates a table with 2 list boxes and buttons to add/remove from one list box to another. I want to insert this table into the Edit Dialog box of the JQGrid. So that when the add or edit button is clicked the table displays and the user can add items and the corresponding cell is edited.
Java script and AJAX:
function create_listbox() {
var html = '<select id="ddlRoles" size="7" multiple></select>';
var selected = '<select id="ddlSelectedRoles" size="7" multiple></select>';
var table = '<table id="table1" border="3"></table>';
var tr = '<tr id="tr1"></tr>';
var td1 = '<td id="td1"></td>';
var td2 = '<td id="td2"></td>';
var td3 = '<td id="td3"></td>';
var addButton = '<button id="add" onclick="addRole()">Add Role</button><br>';
var removeButton = '<button onclick="removeRole()">Remove Role</button><br>';
$('#whatever').append(table);
$('#table1').append(tr);
$('#tr1').append(td1);
$('#tr1').append(td2);
$('#tr1').append(td3);
$('#td1').append(html);
$('#td2').append(addButton);
$('#td2').append(removeButton);
$('#td3').append(selected);
$.ajax({
url: "MyApplication.asmx/GetRoles",
data: "{ }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
// alert(data.d);
for (var i = 0; i < data.d.length; i++) {
$('#ddlRoles').append("<option value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ":" + errorThrown);
}
});
}
I know that I need an EditTypeCustomElement and EditTypeGetCustomValue but I am completely stumped as to how to accomplish this.
I've tried returning $table.get(0) with the create_listbox function which adds a table but it doesn't add the child elements. Any help?
You need a EditTypeCustomElement (below) JQuery and Ajax:
function create_listbox(value, options) {
var htmlRolesDdl = '';
var htmlRolesSelectedDdl = '';
$.ajax({
url: "MyApp.asmx/GetRoles",
data: "{ }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
var roles = new Array();
if (value.toString().match(',') == null) roles.push(value.toString());
else roles = value.toString().split(",")
for (var i = 0; i < data.d.length; i++) {
var isMatch = false;
for (var j = 0; j < roles.length; j++) {
if (data.d[i].RoleName == roles[j].toString()) {
htmlRolesSelectedDdl += "<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>";
//$selected.append("<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
isMatch = true;
}
}
if (!isMatch) {
htmlRolesDdl += "<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>"
//$listbox.append("<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
}
}
},
async: false,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ":" + errorThrown);
}
});
var html = '<table id="UserRole" border="0">';
html += '<tr>';
html += '<td>';
html += '<select id="ddlRoles" size="7" multiple width="155" style="width:155px;">';
html += htmlRolesDdl;
html += '</select>';
html += '</td>';
html += '<td>';
html += '<button onclick="addRole()" style="width:100px;"> Add >></button><br>';
html += '<button onclick="removeRole()" style="width:100px;"><< Remove</button><br>';
html += '</td>';
html += '<td>';
html += '<select class="ListBoxStyle" id="ddlSelectedRoles" size="7" width="155" multiple style="width:155px;">';
html += htmlRolesSelectedDdl;
html += '</select>';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td colspan="3" align="center" style="padding-top:5px;padding-bottom:10px;">';
html += '(Press and Hold "Ctrl" to select multiple roles)';
html += '</td>';
html += '</tr>';
html += '</table>';
return $(html);
}
and a EditTypeGetCustomValue (below) JQuery and AJAX:
function listbox_value(elem, type, stringvalue) {
if (type == 'get') {
var roles = new Array();
$("#ddlSelectedRoles > option").each(function () {
roles.push($(this).val().toString());
});
return roles.toString();
} else if (type == 'set') {
var roles = new Array();
$("#ddlSelectedRoles > option").each(function () {
roles.push($(this).val().toString());
});
$("#<%= hdnSelectedRoles.ClientID %>").val(roles);
return roles.toString();
}
}

How to load images on page refresh from folder using Asp.Net

I would like to know that On Page refresh I would like to display more than 40+ images which are already existed in my server folder to be displayed in a div control which already exists and add those images to that div
As of now I can display one image using as shown below:
Preview.ImageUrl = "~/DownloadImages/" & Session("tempDir").ToString & "/" & filename
I would like to know the better solutions!
Here is how the images are generated:
<script type="text/javascript">
$(function () {
$("#<%=uploader.ClientId%>").plupload({
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: 'Default.aspx',
max_file_size: '10mb',
max_file_count: 21,
chunk_size: '1mb',
unique_names: true,
rename: true,
dragdrop: true,
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
flash_swf_url: 'js/plupload.flash.swf',
silverlight_xap_url: 'js/plupload.silverlight.xap'
});
$('form').submit(function (e) {
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
if (uploader.files.length > 0) {
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
}
else
//alert('You must at least upload one file.');
return false;
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FilesAdded', function (up, files) {
var i = up.files.length,
maxCountError = false;
plupload.each(files, function (file) {
setTimeout(function () {
up.start();
}, 100);
if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
$.msgBox({
title: "Info",
content: "Max Files Reached.",
type: "info",
showButtons: true,
opacity: 0.1,
autoClose: false
});
uploader.removeFile(up.files[i - 1]);
} else {
}
});
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FileUploaded', function (up, file, res) {
$('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
showStickySuccessToast();
}
});
});
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
</script>
If I know how many Images users can add then it's easy but It's hard to say thats the main issue.
You can use Literal or Image Controls and add them on a Panel (or even a div if you add runat="server" to it on the aspx file)
<div id="existingDiv" runat="server"></div>
I prefer Image controls... something like this: (this is a very simple example of course)
foreach(string imageURL in urlsList)
{
var img = new System.Web.UI.WebControls.Image();
img.ImageUrl=imageURL;
img.Width = 200;
img.Height = 100;
this.div1.Controls.Add(img);
}
EDIT:
Inside urlsList i load the urls like so: (VB)
Dim urls As New List(Of String) 'I dont know if you need another parenthesis here on VB...
urls.Add("imageurl1")
urls.Add("imageurl2")

JW Player playlist only loads randomly in IE, works fine in FF every time

The playlist loads every time in FF but only the first time in IE (6-8), after that only randomly.
If I alert the error that's thrown I get "TypeError: playerReady is undefined".
My code looks good and obviously works since FF displays the playlist perfectly. I've got no idea how to solve this. Anyone?
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '<%=FlashWidth %>', '<%=FlashHeight %>', '9', '#ffffff'),
playlistURL = '<%=PlaylistURL %>',
imageURL = '<%=GetBackgroundImageUrl() %>';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
if (playlistURL !== '') {
so.addVariable('playlistfile', playlistURL);
so.addVariable('playlist', 'none');
so.addVariable('enablejs', 'true');
}
else {
so.addVariable('file', '<%=FlashURL %>');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview<%=PlayerID %>');
</script>
The playerReady function is called by the player once it's finished it's setup process. Do you happen to define that function and then set it to undefined? That might cause an error.
Also, what version of the player are you using?
so.addVariable('enablejs', 'true');
I don't belive that's been a flashvar since the 3.X player, which is no longer supported.
Best,
Zach
Developer, LongTail Video
Not sure how I solved it, but here is the final code that actually works:
HTML PAGE:
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '700', '345', '9', '#ffffff'),
playlistUrl = 'XML-PLaylist',
imageURL = '/ImageVault/Images/conversionFormat_2/id_1577/scope_0/ImageVaultHandler.aspx';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
so.addParam('wmode', 'opaque');
if (playlistUrl !== '') {
so.addVariable('playlistfile', playlistUrl);
so.addVariable('playlist', 'none');
so.addVariable('controlbar', 'bottom');
so.addVariable('backcolor', '0xDDE5FF');
so.addVariable('frontcolor', '0x142864');
so.addVariable('screencolor', '0xffffff');
so.addVariable('enablejs', 'true');
so.addVariable('overstretch', 'true');
}
else {
so.addVariable('file', '');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview');
</script>
And here's the JavaScript:
try {
var playlistReady = playerReady;
} cat
ch (err) {
//alert('1' + err);
}
playerReady = function(obj) {
setTimeout(function() { checkPlaylistLoaded(obj) }, 1);
try {
playlistReady(obj);
} catch (err) {
//alert(err);
}
}
function itemHandler(obj) {
var item = obj['index'];
var playlist = $("#" + obj['id']).next();
var currentItem = 0;
playlist.children().each(function() {
if (currentItem == item) {
$(this).addClass("playing");
} else {
$(this).removeClass("playing");
}
currentItem++;
});
}
function checkPlaylistLoaded(obj) {
//debugger;
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist();
if (jsPlaylist.length > 0) {
var playlist = createPlaylist(obj);
populatePlaylist(player, jsPlaylist, playlist);
player.addControllerListener("PLAYLIST", "playlistHandler");
player.addControllerListener("ITEM", "itemHandler");
player.addControllerListener("STOP", "showPlaylist");
player.addModelListener("STATE", "stateListener");
} else {
setTimeout(function() { checkPlaylistLoaded(obj) }, 150);
}
}
function stateListener(obj) {
if (obj.newstate === 'PLAYING') {
hidePlaylist();
}
if (obj.newstate === 'PAUSED') {
showPlaylist();
}
}
function createPlaylist(obj) {
var playerDiv = $("#" + obj['id']);
playerDiv.after("<div class='jw_playlist_playlist'></div>");
return playerDiv.next();
}
function hidePlaylist() {
$('.jw_playlist_playlist').animate({ left: "-320px" }, 1000);
}
function showPlaylist() {
$('.jw_playlist_playlist').animate({ left: "-10px" }, 1000);
}
function playlistHandler(obj) {
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist(),
playerDiv = $("#" + obj['id']),
playlist = playerDiv.next();
populatePlaylist(player, jsPlaylist, playlist);
}
function populatePlaylist(player, jsPlaylist, playlist) {
playlist.empty();
for (var i = 0; i < jsPlaylist.length; i++) {
var jsItem = jsPlaylist[i];
var alternate = "even";
if (i % 2) {
alternate = "odd";
}
playlist.append("<div id='" + getItemId(jsItem) + "' class='jw_playlist_item " + alternate + "'>" + dump(jsItem) + "</div>");
}
var playlistItem = 0;
playlist.children().each(function() {
var currentItem = playlistItem;
$(this).click(function() {
player.sendEvent("ITEM", currentItem);
});
playlistItem++;
});
}
function getItemId(arr) {
var output = '${link}',
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dump(arr) {
var output = "<div class='jw_playlist_title'>${title}</div><div class='jw_playlist_description'>${description}</div>",
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dumpText(arr) {
var dumped_text = "";
if (typeof (arr) == 'object') {
for (var item in arr) {
var value = arr[item];
if (typeof (value) == 'object') {
dumped_text += "<div class='" + item + "'>";
dumped_text += dump(value);
dumped_text += "</div>";
} else {
dumped_text += "<div class='" + item + "'>" + value + "</div>";
}
}
} else {
dumped_text += arr + " (" + typeof (arr) + ")";
}
return dumped_text;
}
function getVars(str) {
return str.match(/\$\{(.*?)\}/g);
}

Resources