Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVC

Filed in ASP.NET MVC | C# | jquery 13 Comments

I recently had a requirement for a mapping application that required me to pass in longitude and latitude coordinates. It wasn’t realistic to have the user look those values up, so I had to figure out a way to automatically lookup the coordinates given a zip code.

There are tons of pay services (some of which I use), but for this project needed something free. I stumbled on http://www.geonames.org/ which has a great service. You can see their webservice documentation here: http://www.geonames.org/export/web-services.html.

Ok, let’s get started:

Web form

These are the input fields we will use to perform the lookup. We are going to have three textboxes, one which has an onchange event.

    Zip Code<br/>
    <%= Html.TextBox("Zip", "", new { @onchange = "LookupCoordinates(this.value)" })%>
    <br/><br/>
    Latitude: <%= Html.TextBox("Lat") %>,
    Longitude:<%= Html.TextBox("Lon") %>

jQuery Function

This function is responsible for looking up the latitude and longitude coordinates, and populating the results into the textboxes. Note that I’m wiring in US as the country below. The country is an optional parameter, when entered gives you more relevant results. Otherwise you are going to have to write some kind of loop.

    function LookupCoordinates(zip) {
            $.post("/Home/LookupCoordinates",
            { Zip: zip, Country: "US" },
            function(data) {
                var result = eval('(' + data + ')');
                var coordinates = result.split(",");
                $("#Lat").val(coordinates[0]);
                $("#Lon").val(coordinates[1]);
            });
        }

Call Geonames.org

In this sample, the call to geonames.org is wired into the controller. In real life, you probably want to wrap it in some kind of helper or service class. There are a few using statements you will need:

using System.IO;
using System.Net;
using System.Xml;

The above namespaces are important because we are going to make a WebRequest, and then parse the Xml results. The webservice method we are going to call is:

http://ws.geonames.org/postalCodeSearch?postalcode=78702&maxRows=10&country=US

Since we know the Zip and the Country, we should in theory only get 1 result. Below is a screenshot of the elements returned for our 78702 search (Austin):

Onto the method:

    public ActionResult LookupCoordinates(string Zip, string Country)
    {
        string Lat = "";
        string Lon = "";
        string PostUrl = "http://ws.geonames.org/postalCodeSearch?postalcode=" + Zip + "&maxRows=10&country=" + Country;
        WebResponse webResponse = webRequest.GetResponse();
        if (webResponse == null)
        { }
        else
        {
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string Result = sr.ReadToEnd().Trim();
            if (Result != "")
            {
                // Load the response into an XML doc
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(Result);
                //  Navigate to latitude node
                XmlNodeList name = xdoc.GetElementsByTagName("lat");
                if (name.Count > 0)
                {
                    Lat = name[0].InnerText;
                }
                //  Navigate to longitude node
                name = xdoc.GetElementsByTagName("lng");
                if (name.Count > 0)
                {
                     Lon = name[0].InnerText;
                }
            }
        }
        return Json(Lat + "," + Lon);
    }

From there, the method returns the latitude and longitude in a comma separated string, the javascript call splits the results and populates each respective text box. Below is a video preview – really short, really lame, but you get to see the code in action:

,

TinyMCE samples with ASP.NET MVC

Filed in ASP.NET MVC | C# | Html | jquery 3 Comments

After using Telerik’s RadEditor control for years with all my asp.net web form applications, I found myself looking for a javascript alternative when I moved up to MVC. Having paid top dollar for RadEditor (which is a fine product!) and never used TinyMCE, I couldn’t imagine something free could be that good. Well it is! And really easy to use–whether in c#, vb, php, etc.–plus no nasty viewstate to bloat your page.

You can download code samples here.

Downloading files

The first step is visiting the TinyMCE website and downloading the files: http://tinymce.moxiecode.com/download.php. Make sure you select the “jQuery package” link.

Extract the zip file, and copy the actual script files (tinymce\jscripts directory) into a folder in your project. I typically have a scripts folder, and create a “tiny_mce” subdirectory to hold the files.

Setting references

If you have a master page, just add the following line into the top of the master page:

<script type="text/javascript" src="<%=Url.Content("~/scripts/tiny_mce/tiny_mce.js") %>"></script>

Otherwise add the same line to the top of each page that will use the TinyMCE editor. Next, you initialize the textareas to use TinyMCE. The following javascript snippet initializes every textarea on the page (or every single page if added in the master page) using the defaults:

<script type="text/javascript">

tinyMCE.init({
mode: "textareas",
theme: "advanced"
});

We will dive deeper into configuring the available buttons.

Samples

TinyMCE in a dialog

One common need is allowing users to edit text in a modal window. Combining jQuery’s dialog (http://www.billsternberger.net/asp-net-mvc/jquery-modal-dialog-without-the-x-button/) with TinyMCE is a simple and elegant solution.

First, initialize the dialog and add the click event to show the editor:

$(function() {
$("#texteditorform").dialog({
height: 300,
width: 520,
autoOpen: false
});
});

function ShowModalEditor() {
$("#texteditorform").dialog('open');
}

Next, add the button to show the editor:

<a onclick="ShowModalEditor()" href="#">Show modal text editor</a>

Next, create the dialog div with the textarea inside:

<div title="Text Editor" id="texteditorform">
Add something below:<br />
<textarea rows="5" cols="25" id="modalTextarea"&gt;&lt;/textarea><br /><br />
<input type="button" onclick="CloseModalEditor()" value="Save" /><br />
</div>

Toggle TinyMCE editor and textarea

Occasionally you may want to allow users to toggle between the advanced editor and the regular textarea. There is a simple function to pull this off. First, add the javascript function to handle the toggling:

function toggleEditor(id) {
if (!tinyMCE.get(id)) {
tinyMCE.execCommand('mceAddControl', false, id);
}
else {
tinyMCE.execCommand('mceRemoveControl', false, id);
}
}

Next, add a button that will allow the user to toggle:

<a href="#" onclick="javascript:toggleEditor('toggleTextarea');">Toggle</a>

Validate input value

To validate the user input of a TinyMCE-enabled editor, the standard jqeuery $(“#field”).val() method won’t work.  Instead, you need to use a TinyMCE method instead:

var theValue = tinyMCE.get('valueTextarea').getContent();

Make TinyMCE editor Read Only

Should you need to initialize a TinyMCE editor as readonly, all you have to do is add a line to the init:

$(function() {
$("#texteditorform").dialog({
<span style="color: #0000ff;">readonly: true</span>
});
});

Customize TinyMCE Editor buttons

Include underline, copy, paste, and other formatting options in toolbar

Customizing which buttons appear on the toolbar is really easy, below are some sample configurations. Setting and aligning the buttons are done in theme_advanced properties.

tinyMCE.init({
mode: "textareas",
theme: "advanced",
plugins: "style,iespell,searchreplace,contextmenu,paste,html",

//  Theme options #1
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
theme_advanced_buttons4: "",

//Theme options #2
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,|,fontselect,fontsizeselect",
theme_advanced_buttons2: "",

// Align and place toolbar
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The above are the two standard configurations I use. To view a full list of buttons, click here.

, , , ,

Use jQuery to change a form’s action url

Filed in ASP.NET MVC | Html | jquery 5 Comments

This is another quick and dirty post, more for future reference when I need to access this snippet again! The scenario is if you have one form on a page, but want to change the target on the fly for whatever reason. Here are the two magical lines:

$("form").attr("action", "/ControllerName/Method");
$("form").submit();

,

Microsoft and Google jQuery CDN Link

Filed in Html | jquery 2 Comments

So what is a Content Delivery Network (CDN)?

In a nutshell, a CDN is a network of computers strategically placed around the world that serve up cached content to users. The content types include images, videos, style sheets, and in this case,  script libraries. As you can imagine, your pages will load faster when browsers are downloading these objects from a server closer to them than from one central location half way across the globe.

When it comes to jquery, there are two main CDNs I’ll reference in projects: Microsoft’s and Google’s. Adding a reference to either CDN is really easy. All you have to do is add one of the following lines into your page header.

Microsoft’s jQuery CDN reference:

<script src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js” type=”text/javascript”></script>

Google’s jQuery CDN reference:

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js” type=”text/javascript”></script>

That’s it!

, , , ,

Top 10 jQuery Functions and Plugins (Part II)

Filed in jquery Leave a comment

The following is the second part of a set of jQuery shortcuts I use at some point on a daily basis. If you missed part I, you can see them here.

5. Lightbox 2

Why do I like this? It is simple to integrate and very elegant looking. Need to group images together so the user can page through a gallery? No problem! adding a rel= lightbox tag to any pictures on a page automatically groups the images instantly.

Read more here: http://www.lokeshdhakar.com/projects/lightbox2/

4. $.post

$.post is another powerful function that allows you to do a http post to the server and get back a response which you can then parse and do something with. You can check out my $.post example where I use $.post in conjunction with MVC and a JsonResult.

Read more here: http://docs.jquery.com/Ajax/jQuery.post

3. Watermark

The old AJAX Control Toolkit had a decent textbox watermark control, but when I moved from WebForms to MVC, wanted to find a better jQuery solution. This plugin is simply awesome. It covers everything from your basic textbox watermark to multi-line watermarks for textareas to dynamic watermarks to WebKit support.

Read more here: http://code.google.com/p/jquery-watermark

2. Curvycorners

This is more for style, it helps out programmers like me that can make things look “not ugly” and that’s about it. Using some good old-fashioned javascript, you can turn a boring div into a sleek looking table.

Read more here: http://www.curvycorners.net/

1. Dialog

This awesome wrapper can be found on the jquery.com website in their UI section. You can style and customize a dialog/popup to autoopen when the page loads, display modal, close on escape, allow resizing, etc. It seems that every application I develop needs some type of advanced confirm box, and the dialog always bails me out. A more advanced use of the dialog can be in conjunction with an html table to perform a quick edit for a grid, which will be the subject of a future post.

Read more here: http://jqueryui.com/demos/dialog/

Hope you found this post useful! If there are any others you like feel free to share below.

, , , , ,

Dynamically Changing the iframe src in jQuery

Filed in Html | jquery 1 Comment

This little function allows you to dynamically change the content of an iframe, using jQuery and javascript. It is perfect if you have a single page where you want to preview other websites without navigating away. To pull this off, you need a textbox, a link, and an iframe:

Enter website url below:<br/>
<input type="text" value="http://www.google.com" name="ifrmSite" id="ifrmsite"/> <a href="#" onclick="Navigate()">Navigate</a>
<br /><br />
<iframe name="iframe1" id="iframe1" src="http://www.google.com" width="600" height="700" scrolling="auto">
</iframe>

Next we add the javascript:

function Navigate() {
var newurl = $('#ifrmSite').val();
$('#iframe1').attr('src', newurl);
window.frames["iframe1"].location.reload();
}

And we’re done!

, ,

Javascript, jQuery Rich text editor

Filed in C# | Html | jquery Leave a comment

I did a post earlier today (yes, I’m on a roll while jr. is sleeping!) on my Top 10 favorite jQuery functions and plugins. This post is dedicated to one of them: TinyMCE. In the past I’ve used editors like Telerik’s RAD Editor and obout’s Html Editor, both very powerful editors. I was turned on to TinyMCE not too long ago, and haven’t looked back since.

Integrating TinyMCE into any ASP.NET project (MVC included) is really easy, this post will cover the basics of setting up TinyMCE, and then some of the different variations available.

Setup TinyMCE

After you download TinyMCE, copy all the files into your project. Typically I’ll drop the TinyMCE folder into my “Scripts” directory. Once copied, you add a reference in either your page’s header:

<script type="text/javascript" src="<%=Url.Content("~/scripts/tiny_mce/tiny_mce.js") %>"></script>
1

<h2>Initialize TinyMCE</h2>
This is where the fun begins. You can show all the possible buttons, or just a subset of buttons if you need to keep it simple. Below is a "keep it simple" scenario, where only the most basic buttons are presented to the user:

1
tinyMCE.init({
mode: "textareas",
theme: "advanced",
plugins: "style,iespell,searchreplace,contextmenu,paste,html",

// Theme options
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The theme_advanced_buttons1 – 4 represent the rows where the buttons will appear. If you have a really wide textarea, you could theoretically show all the buttons on a single row. Consult the TinyMCE documentation for a detailed list of every single button.

Next is the generic “advanced” configuration I’ll use when I have a more savvy user. It gives users a html button so they can modify the markup:

tinyMCE.init({
mode : "textareas",
theme : "advanced",

theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

There are also times where I want to keep the custom toolbar, but also allow the user to show/hide the html. To accomplish that, you can add this hyperlink:

<a href="#" onclick="ToggleEditor('textareaID');">Show/Hide Html</a>

And this function:

function ToggleEditor(id)
{
if (!tinyMCE.get(id)) {
tinyMCE.execCommand('mceAddControl', false, id);
}
else {
tinyMCE.execCommand('mceRemoveControl', false, id);
}
}

, , ,

Using jQuery to enable and disable radio buttons onclick

Filed in Html | jquery Leave a comment

This is by far the funnest pieces of code I’ve written in a long time. So simple, so stupid, so useful! The scenario is you want users to click a radio button from a series of options…but only after they choose a parent radio button. In this example we want the user to select only one city from one state.

Add the radio buttons

I’m going to keep this simple, so we’ll have only two parent radio buttons:

<input type="radio" name="rdoState" value="Texas"  onclick="EnableTexas()" />
<div id="DivTexas">
<input type="radio" name="rdoTexas" value="Austin" />Austin<br/>
<input type="radio" name="rdoTexas" value="Dallas" />Dallas<br/>
<input type="radio" name="rdoTexas" value="Houston" />Houston<br/>
</div>
<br/><br/>
<input type="radio" name="rdoState" value="Virginia"  onclick="EnableVirginia()" />
<div id="DivVirginia">
<input type="radio" name="rdoVirginia" value="Arlington" />Arlington<br/>
<input type="radio" name="rdoVirginia" value="McLean" />McLean<br/>
<input type="radio" name="rdoVirginia" value="Reston" />Reston<br/>
</div>

Add jQuery function for onclick event

We are going to add two functions, and one initialization routine to disable all the child radio buttons by default. First, we initialize everything to be unchecked and disabled, pretty self-explanatory:

$(function() {
//init Texas
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//init Virginia
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
});

Next we add the two onclick functions:

function EnableTexas()
{
//disable Virginia options
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
//enable Texas options
$('#DivTexas :input').removeAttr('disabled');
}

function EnableVirginia()
{
//disable Texas options
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//enable Virginia options
$('#DivVirginia :input').removeAttr('disabled');
}

,

Top 10 jQuery Functions and Plugins (Part I)

Filed in Html | jquery 1 Comment

The following is a set of jQuery shortcuts I use at some point on a daily basis.

10. appendTo()

While there are many ways to use appendTo(), I find myself taking advantage of it when dealing with dual listboxes. With that one little command, I can move listitems from one listbox to another with no crazy loops. To illustrate the ease of use, here the entire function corresponding to the “add all items” button:

jQuery(“#availableItems option”).appendTo(“#selectedItems”);

Read more here: http://docs.jquery.com/Manipulation/appendTo

9. html()

The html attribute allows you to get or set the innerHTML of an element. Typically I’ll have a div to handle some kind of validation results, and populate it based upon some logic. For example, here is a div to hold the results:

<div id=”someresults” style=”display:none;”></div>

Then some function to populate it, in this case, display an error:

function someFunction()
{
$(“#someresults”).show();
$(“#someresults”).html(“<h2 style=’color:red;’>Something bad happened…</h2>”);
}

While that example is pretty vanilla, you can imagine how far you can stretch this.

Read more here: http://docs.jquery.com/Attributes/html

8. val()

If you plan on doing any kind of form manipulation, this one’s a must! The val attribute gets/sets a form field’s value. When called with a value like here:

$(“#firstName”).val(“William”);

The value of the firstName textbox is overwritten with William. To read the value, you simply call without an argument:

var theFirstName = $(“#firstName”).val();

One fun way to use the val attribute is creating the classic “billing address is the same as the mailing address” checkbox button. Here is how the code would look:

$(“#BillingAddress1″).val($(“#MailingAddress1″).val());
$(“#BillingAddress2″).val($(“#MailingAddress2″).val());
$(“#BillingCity”).val($(“#MailingCity”).val());
$(“#BillingState”).val($(“#MailingState”).val());
$(“#BillingZip”).val($(“#MailingZip”).val());
$(“#BillingCountry”).val($(“#MailingCountry”).val());

Read more here:  http://docs.jquery.com/Attributes/val

7. TinyMCE

Back when I used to exclusively program in ASP.NET 2.0, Telerik’s RAD Editor (http://demos.telerik.com/aspnet-ajax/editor/examples/overview/defaultcs.aspx) was the coolest thing ever. It is still really cool with some really advanced features, but for projects with a tight budget, found an awesome free tool in TinyMCE.

While there are unlimited numbers of configurations, I’ll typically use it in one of two modes:

1. I’ll convert all textareas into rich text editors, usually for an admin master page

2. Initialize individual textareas as needed

Initializing the textbox is the same, the difference is where you call it. Here is how you initialize the editor:

tinyMCE.init({
mode : “textareas”,
theme : “advanced”,

theme_advanced_toolbar_location: “top”,
theme_advanced_toolbar_align: “left”,
theme_advanced_resizing: true,
readonly: false
});

Read more here:  http://tinymce.moxiecode.com

6. tablesorter 

This might be one of my favorite plugins of all! This jQuery plugin converts a generic html table into a sorting machine, with the smarts to distinguish between dates, integers, markup, etc. baked right in. Like TinyMCE, you can initialize every table to be sortable, or on an individual basis. There is also an optional paging add-on which works decently, although I tend to go with my own personal paging control. So what do you need to do?

1. Add the reference to the plugin, then the following javascript:

jQuery(document).ready(function() {
jQuery(“table”)
.tablesorter({ widthFixed: true, widgets: ['zebra'] })
});

2. Set the table’s class to tablesorter, and include <thead> and <tbody> tags.

The link above takes you to the detailed documentation and how far you can bend and flex this plugin. But if you need to support sorting, this is one powerful plugin.

Read more here:  http://tablesorter.com/docs/

Stay tuned for Part II!

, , , ,

Autocomplete using Html, JSON, MVC, jQuery

Filed in ASP.NET MVC | C# | jquery 6 Comments

I found an awesome AutoComplete tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) using PHP, jQuery, MySQL, and decided to port it over to Microsoft’s ASP.NET MVC. Turned out to be way easier than I thought! You can download the auto-complete code sample here.

Configure MVC Controller

So this is basic: create a JsonResult method in your controller that runs a query. I’m using nHibernate and ActiveRecord to perform a top 10 query as you can see here:

public JsonResult GetCountry(string searchString)
{
StringBuilder sb = new StringBuilder();
ICriterion[] query = { Expression.Eq("Code", "COUNTRYLIST"), Expression.Like("Value",searchString, MatchMode.Start) };
LookupCode[] countries = LookupCode.SlicedFindAll(0, 10, query);
for (int i = 0; i < countries.Length; i++)
{
sb.Append("<li onClick=\"fill('" + countries[i].Value + "');\">" + countries[i].Description + "</li>");
}
return Json(sb.ToString());
}

Create jQuery Function

There are two jQuery functions we need. The first function simply calls the GetCountry method:

function lookup(inputString) {
$.post("/LookupCode/GetCountry", { searchString: "" + inputString + ""},
function(data) {
var myObject = eval('(' + data + ')');
if (data.length > 0) {
$("#suggestions").show();
$( "#autoSuggestionsList").html('<ul>' + myObject + '</ul>');
}
});
}

The second method is called from the auto-suggest list, and its job is to populate the selected value into the form field and to hide the auto-suggest list:

function fill(thisValue) {
$("#Country").val(thisValue);
setTimeout("$("#suggestions").hide();", 200);
}

Prep Textbox

There are two things we need to do to configure the textbox to trigger the auto-complete functionality:

1. Add the onkeyup=”lookup(this.value);” attribute within the input:

<input type="text" name="Country" id="Country"  onkeyup="lookup(this.value);"  />

2. Add a DIV to hold the suggestion list:

<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>

That’s it! For extra credit, we can add some style in the next step.

Add Style

The following style was taken and modified from the original tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) , and is really easy to customize:

.suggestionsBox {
position: relative;
left: 5px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #e4e4e4;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #336699;
color:#333333;
}

.suggestionList {
margin: 0px;
padding: 0px;
}

.suggestionList ul {
margin: 0px;
padding: 0px;
}

.suggestionList li {
list-style-type: none;
margin: 0px 0px 0px 0px;
padding: 3px;
cursor: pointer;
}

.suggestionList li:hover {
list-style-type: none;
color:White;
background-color: #336699;
}
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 106px; width: 1px; height: 1px;">function lookup(inputString,prefix) {
if (inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("/LookupCode/GetCountry", { id: "" + inputString + "", prefix: prefix },
function(data) {

var myObject = eval('(' + data + ')');
var suggestlist = "#" + prefix + "autoSuggestionsList";
var suggestfield = "#" + prefix + "suggestions";

if (data.length > 0) {

$(suggestfield).show();
$(suggestlist).html('<ul>' + myObject + '</ul>');
}
});
}
}
</div>

, , , , , ,

TOP