Wednesday, April 12, 2017

Sorting of <li> elements using jQuery sort() not working (refresh page only) in ASP.NET

Given the simple sorting code below which changes the order of <li> elements to ascending order and assuming that the text content of each li elements are numbers.
$(function () {
 $('#sortList').click(function (e) {
  // Select all the li items
  var numbersList = $('#numbersList li');
  
  numbersList.sort(function (a, b) {
   return parseInt($(a).text(), 10) > parseInt($(a).text(), 10);
  }).appendTo(numbersList.parent());
 });
});
The code should work only to find out that the page will only refresh after the button click. And then the re-arranging of the elements are discarded. The simple fix to this issue is to add the preventDefault() to prevent the button's default behavior that is to post back.
$(function () {
 $('#sortList').click(function (e) {
         //add preventDefault() to reflect the changes after sorting
  e.preventDefault();
  // Select all the li items
  var numbersList = $('#numbersList li');
  
  numbersList.sort(function (a, b) {
   return parseInt($(a).text(), 10) > parseInt($(a).text(), 10);
  }).appendTo(numbersList.parent());
 });
});
Fiddle: Sort Unordered list items

Saturday, April 8, 2017

$.getJSON() not loading JSON file within Visual Studio Project in ASP.NET WebForms

Hi,
I was trying to load a JSON file located within my Visual Studio project using $.getJSON(), however the code below doesn't work as expected.
$.getJSON('/Assets/misc/employee.json', function (data) {
 alert('processing!');
})
.done(function (r) {
 alert(r.message);
})
.fail(function (s) {
 alert('oops the file is missing!');
});
After investigating for a few hours, I tested the local path of the JSON file such as http://localhost:3766/Assets/misc/employee.json and the result was an exception "HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.".
I remember the solution in one of my ASP.NET project was to set the MimeMap in the web.config inside the system.webServer element. After setting the MimeMap for json files, I can now load local JSON files using $.getJSON().
<system.webServer>
 <staticContent>
   <mimeMap fileExtension=".json" mimeType="application/json" />
 </staticContent>
</system.webServer>

:-)

Friday, April 7, 2017

Visual Studio showing only "Attach" and no Debug options in ASP.NET Project

Hello,
Last night my computer shuts down unexpectedly due to power outage and when I opened an ASP.NET project this morning, it only shows "Attach" in the debug options. Running to different browsers such as Google Chrome, Firefox and Internet Explorer were missing.
After a few search, I encountered a solution which is to set again the ASP.NET Project as StartUp Project by right clicking the project and selecting the option Set as StartUp Project.
That's it.. :-)