Store images on Flickr using Flickrnet.dll and ASP.NET MVC

Filed in ASP.NET MVC | C# 3 Comments

For one of my recent projects I had to use Flickr as an image repository, so this code just shows how I was able to do that with the help of the fantastic Flickrnet.dll library. You can download the latest Flickrnet library here: http://flickrnet.codeplex.com/. You can also download the article’s full working Flickr demo code.

Getting Started

Before we dive into the MVC portion, you have to make sure you have installed the flickrnet.dll file, referenced it, and added the appropriate web.config elements.

configSections element

Append the following element after the default sectionGroup:
<section name="flickrNet" type="FlickrNet.FlickrConfigurationManager,FlickrNet"/>

And setup your database connection strings

Flickrnet element

Add the following element before the appSettings element:
<flickrNet apiKey="YOUR_API_KEY" secret="YOUR_SECRET" cacheDisabled="true"/>

appSettings element

Add the following keys to the appSettings element:

<add key="FlickrAuthtoken" value="YOUR_FROB/TOKEN" />
<add key="FlickrUserId" value="YOUR_USERID"/>


Click on the thumbnail for a larger view


That is all you need to do in web.config. You get your apikey and secret through flickr. An awesome article off the flickrnet.codeplex site covers how to get your FROB/Token: http://blogs.msdn.com/coding4fun/archive/2006/11/22/1126978.aspx.

Database Setup

The images are going to be uploaded to Flickr, but we are going to keep references to the images in the database for later retrieval. Here is the table script if you are using MySQL:

CREATE TABLE  `sampledb`.`Image` (
  `ImageID` int(11) NOT NULL AUTO_INCREMENT,
  `ImageURL` varchar(250) DEFAULT NULL,
  `Tags` varchar(150) DEFAULT NULL,
  `FlickrID` varchar(50) DEFAULT NULL,
  `ImageURLThumbnail` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`ImageID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

or if you are using SQL Server:

CREATE TABLE  [SampleDB].[dbo].[Image] (
  ImageID int NOT NULL IDENTITY,
  ImageURL varchar(250) DEFAULT NULL,
  Tags varchar(150) DEFAULT NULL,
  FlickrID varchar(50) DEFAULT NULL,
  ImageURLThumbnail varchar(250) DEFAULT NULL,
  PRIMARY KEY (ImageID)
);

Once the database is setup, all we have left is the code for uploading, storing, and retrieving the images.

Uploading Images into Flickr

This part is easier than you think. We start out with a typical upload form. For this sample we are going to only have a file input control and a textbox to store our tags:

<form method="post" enctype="multipart/form-data" id="form1" action="/Home/Index">
        <b>Image</b><br />
        <input type="file" name="NewImageName" id="NewImageName" />
        <br /><br />
        <b>Tags</b><br />
        <input type="text" name="NewImgTags" id="NewImgTags" />
        <br />
        <input type="submit" value="Upload" />
    </form>

Nothing controversial there, moving on to the controller is where we find the meat. The first thing the controller needs is a reference to the Flirckrnet.dll and to System.Configuration, so you add your using statements:

using FlickrNet;
using System.Configuration;

Next up is creating the Index post method. Here, we reference the Flickrnet object and upload the photo. At this point, Flickr takes the image, and depending upon the size and dimensions, will resize it into any of five different sizes: square, thumbnail, small, medium, and large.

We then loop through the different sizes Flickr sends back, and store the thumbnail and large image urls into our table. Below is part of the controller method that uploads the image, and then loops through the sizes. You can download a full working sample here.

var flickr = new Flickr
{
    AuthToken = ConfigurationManager.AppSettings["FlickrAuthtoken"]
};

//
//  Upload the image, title, tags, security settings
//
var flickr_id = flickr.UploadPicture(file.InputStream, ImageTitle, ImageDescription, ImageTags, IsPublic,IsFamily,IsFriends);

//
//  Loop through links to resized images up on flickr
//  and store in the database
//
var flickrPhotos = flickr.PhotosGetSizes(flickr_id);

Image newImage = new Image();
newImage.FlickrID = flickr_id.ToString();

//
//  I only care about the thumbnail and the large image, but
//  you can store all of them (when applicable)
//
for (int i = 0; i < flickrPhotos.SizeCollection.Length; i++)
{
    switch (flickrPhotos.SizeCollection[i].Label)
    {
        case "Square":
            break;
        case "Thumbnail":
            newImage.ImageURLThumbnail = flickrPhotos.SizeCollection[i].Source;
             break;
        case "Small":
             break;
        case "Medium":
             break;
        case "Large":
             newImage.ImageURL = flickrPhotos.SizeCollection[i].Source;
             ViewData["NewUrl"] = flickrPhotos.SizeCollection[i].Source;
             break;
    }
}

newImage.Tags = ImageTags;
newImage.CreateAndFlush();

The code sample then sends the large image url from Flickr back down to the browser to preview. Below is a video of the code in action:

, ,

Update textbox with ASP.NET, MVC, jQuery

Filed in ASP.NET MVC | jquery Leave a comment

This post arrives to you today from the awesome Hotel Dunn Inn in beautiful San Jose, Costa Rica! Best. Beds. Ever. It was time to clear the brain and work on some pet projects, and of course code.

In this sample we will look at updating values in textboxes, and then notifying the user of the results. The scenario would be having an Excel-style grid where the user can tab from field to field saving cell values with the onchange event.

Adding References

For this exercise, you just need a reference to the jquery library:

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

<h2>Setting up the Html Form</h2>
We are going to add three textboxes--each with an onchange event--along with a div to hold the result. In real life, the 1, 2, and 3 values would be the item IDs.

1
    <div id="resultmessage" style="width:550px;"></div>
    Textbox 1<br />
    <input type="text" name="textbox1" id="textbox1" onchange="Update('1',this.value);" />
    <br /><br />
    Textbox 2<br />
    <input type="text" name="textbox2" id="textbox2" onchange="Update('2',this.value);" />
    <br /><br />
    Textbox 3<br />
    <input type="text" name="textbox3" id="textbox3" onchange="Update('3',this.value);" />
    <br /><br />

Whenever a user tabs off each box, it will trigger and update to the database. To do that, we add a jQuery function. The function is simple:

  • Use jQuery $.post to send the text change to your controller method
  • Check the result from the controller
  • Display the success or error message

Below is the entire function:

function Update(id, val) {
            $.post("/ControllerName/UpdateTextbox",
            {
                ID: id,
                Value: val
            },
            function(data) {
                <div style='color:blue;'>var myObject = eval('(' + data + ')');
                var saveresult = myObject;</div>
                if (saveresult != "") {
                    $("#resultmessage").html("<div style='display:block; background-color: Red; color: White; font-size: 18px; font-weight: bold; padding: 10px 10px 10px 10px;'>Oops! " + saveresult)
                    $("#resultmessage").show('slow');
                    setTimeout("$('#resultmessage').hide('slow');", 2500);
                }
                else {
                    $("#resultmessage").html("<div style='display:block; background-color: Green; color: White; font-size: 18px; font-weight: bold; padding: 10px 10px 10px 10px;'>Saved!")
                    $("#resultmessage").show('slow');
                    setTimeout("$('#resultmessage').hide('slow');", 2500);
                }
            });
        }

The final piece is a method in a controller–which is pretty vanilla–with one minor twist: instead of an ActionResult, we are going to use a JsonResult:

    public JsonResult UpdateTextbox(string ID, string Value)
    {
        //This is where you would update the database
        string result = (Value.ToLower().StartsWith("r")) ? "ID doesn't exist" : "";
        return Json(result);
    }

Below is a little video clip of the sample in action.

Check username availability with jQuery, ASP.NET MVC, C#

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

This post shows how to add dynamic username availability lookup to an ASP.NET MVC view, using jQuery and C#. There are three parts to the solution: the html form, jQuery function, and the controller.

Html form

This part is pretty simple: a textbox for the username field with an onchange event, a div to hold the lookup results, and a lookup button.

    <h3>Username</h3>
    <%= Html.TextBox("Username", "", new { @onchange = "CheckAvailability()" })%>
    <div style="display:inline;" id="usernamelookupresult"></div><br/>
    <input type="button" value="Check Availability" onclick="CheckAvailability()" />
</code>

jQuery Username Lookup

This is where the magic happens. Well, nothing really magical, just a jQuery call to a controller, passing in the username value. In the example below, the function processing the result looks for a 0 to indicate the username is available. You can modify that to be whatever you want.


    function CheckAvailability() {
        $.post("/Home/CheckAvailability",
        { Username: $("#Username").val()},
            function(data) {
                var myObject = eval('(' + data + ')');
                var newid = myObject;
                if (newid == 0) {
                    $("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
                }
                else {
                    $("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
                }
        });
    }

Controller

This is where your business logic lives, and is where the lookup occurs. For this exercise, we are keeping it simple, but you can see where to add your database lookup.


    public ActionResult CheckAvailability(string Username)
    {
            int Taken = 0;
            //  This is where you add your database lookup
            if (Username == "username")
            {
                Taken = 1;
            }
            return Json(Taken);
    }

Download Sample Application

Below is a quick clip to show the code from the downloadable sample in action:

,

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:

,

Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures

Filed in ASP.NET MVC | C# | jquery 1 Comment

This post extends an earlier post I wrote for a basic auto complete/auto suggest textbox.

In this version, we are going to return a list of our favorite social media websites, by adding a new method to the prior post’s controller which allows thumbnail pictures to appear in the auto-suggest list.

New MVC Controller Method

We are going to create another JsonResult method in the controller to lookup the websites. For demo purposes, we are going to hardcode the list. In real life, you probably will be pulling the list from a database, which is covered in the earlier post.

public JsonResult GetWebsites(string searchString)
        {
            StringBuilder sb = new StringBuilder();

            //
            //  Creating a static list here for demo purposes. In your system, you probably
            //  will have images generated from the database, disk, flickr, etc.
            //
            List<string> sites = new List<string>();
            sites.Add("Blogger");
            sites.Add("Delicious");
            sites.Add("Digg");
            sites.Add("Facebook");
            sites.Add("Flickr");
            sites.Add("FriendFeed");
            sites.Add("Friendster");
            sites.Add("LinkedIn");
            sites.Add("MySpace");
            sites.Add("StumbleUpon");
            sites.Add("Technorati");
            sites.Add("Twitter");
            sites.Add("Yahoo");
            sites.Add("Yelp");
            sites.Add("YouTube");

            for (int i = 0; i < sites.Count; i++)
            {
                if (sites[i].ToLower().StartsWith(searchString.ToLower()))
                {
                    string ImageUrl = "/images/" + sites[i].ToString() + ".png";
                    sb.Append("<li onClick=\"fill('" + sites[i].ToString() + "');\"><img src=\"" + ImageUrl + "\" border=\"0\">&nbsp;" + sites[i].ToString() + "</li>");
                }
            }
            return Json(sb.ToString());
        }

The big addition is adding the <img> tag into the list item value, that’s it :-) Now for tweaking the jquery function from the orinigal post to call the new method:

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

You can download the fully-function code project here:

Download Sample Application

Below is a video clip of the sample in action:

, , , ,

Import CSV or Tab Delimited Data with C#, ASP.NET MVC

Filed in ASP.NET MVC | C# 3 Comments

In this sample we are going to take a different approach to importing data from the traditional file upload method. This sample has a textarea and a button. Users will open their .csv or .txt file, copy the contents, paste them into the textarea, and submit.

Setting up the form

This part is pretty basic:

<textarea id="bulkcsvlist" name="bulkcsvlist" rows="20" cols="105"></textarea>
<input type="submit" value="Upload File" />

Create import method

This sample shows the basics of parsing and adding the records, which assumes is uploading into a Contact table, with the first two fields in the row being FirstName and LastName respectively. You probably want to bake in your security checks and data validation.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadAll(FormCollection f)
{
    string bulkcsvlist = f["bulkcsvlist"].ToString();

    //
    //    Split the rows into an array
    //
    string[] rows = bulkcsvlist.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < rows.Length; i++)
    {
        //
        //    Split the tab separated fields (comma separated split commented)
        //
        //string[] dr = rows[i].Split(new  char[] {','});
        string[] dr = rows[i].Split(new char[] { '\t' });

        //
        //    Add Contact for current row
        //
        if (dr.Length > 0)
        {
                Contact c = new Contact();
                c.FirstName = dr[0].ToString();
                c.LastName = dr[1].ToString();
                c.CreateAndFlush();
                c = null;
        }
    }
}

Normally I’ll throw each successful add into a List<> so whoever is uploading can validate the records look right or do any post-upload polishing, and the errors into a ViewData to display so the user can fix whatever needs fixing.

If you want a working sample, let me know!

, ,

ASP.NET MVC sample application

Filed in ASP.NET MVC 6 Comments

Below is a fully functional asp.net mvc sample application project. Go ahead a download it, play with it, make suggestions, extend, etc. If you have any suggestions for improvements, just drop me a line or leave a comment.

The sample project assumes you have Visual Studio 2008 installed, the rest of the dlls and javascript files are included in the download (nHibernate, ActiveRecord, jQuery, plugins). Also included are scripts to create the sample table schema for both SQL Server and MySQL.

The following mvc sample projects are included:

  • Auto-Complete Using jQuery
  • Add a Row to a HTML Table
  • Dual Listbox in jQuery
  • TinyMCE Samples
  • Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures
  • Check username availability

IMPORTANT: You need to set the username and password for your database in the web.config file for the project to work.

Below is a video showing the sample in action:

, ,

Dynamically populate dropdownlist in ASP.NET MVC

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

There are a few different ways to dynamically populate a dropdownlist in MVC: you could use a classic ASP old school loop with a bunch of response.writes, you can store the list’s collection into ViewData and use an html helper, or you can use jquery. We’ll look at samples for each way.

Populate dropdownlist with response.writes

We will start out with the least elegant solution, but it does work nonetheless. So this is the code inside your view:

        <select id="ID" name="ID">
            <%
             Contact[] contacts = Contact.FindAll();
             for(int i=0; i < contacts.length;i++){ %>
             <option value="\&quot;&quot;">" + contacts[i].FullName + "</option>
             <% } %>
        </select>

Populate dropdownlist with ViewData

This method is better, and is baked right into MVC. The downside is you can only use it in MVC, and involves using ViewData (detailed ViewData definition), the View and the Controller. First we prepare the Controller:

public ActionResult Index()
{
    Contact[] contacts = Contact.FindAll();
    ViewData["Contacts"] = new SelectList(contacts,"ID","FullName", <span style="color:red;">[Selectedvalue]</span>);
    return View();
}

Selectedvalue – this optional parameter can be used to select a specific value, useful if you are displaying a form in edit mode.

The last part is binding the ViewData contents to a dropdownlist in the View:

    <%= Html.DropDownList("Contacts") %>

Populate dropdownlist with jQuery

This is the most flexible of the three, and can be used in web forms, php, MVC, etc. This method involves a jquery call in javascript:

    <script language="javascript" type="text/javascript">
        $(function() {
            $.getJSON("YOURPATH/Contact/ContactList", function(data) {
                var items = "<option selected></option>";
                $.each(data, function(i, item) {
                    items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
                });
                $("#ContactID").html(items);
        });
    </script>

The above function calls the ContactList method, which returns a ListItem collection. You then loop through the result, and add the options. Finally, the html contents of the dropdownlist are set. The MVC method that returns the contact list looks like this:

        public ActionResult OrganizationList()
        {
            Contact[] contacts = Contact.FindAll();
            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(contacts, "ID", "FullName"));
            }
            return View(contacts);
        }

, ,

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.

, , , ,

jQuery Modal Dialog without the x button

Filed in ASP.NET MVC | CSS | Html | jquery 1 Comment

Found myself wanting to provide a modal dialog (preferably in jQuery of course!) to gate first-time page visitors. The requirements were:

  • On page load, display modal dialog with a form to request basic contact information
  • Disable the “esc” key to force the user to enter the info or click a “no thanks” button
  • Hide the x which appears in the dialog

My approach was using the jQuery dialog, $.post to send the contact information to my controller and then hide the modal dialog. We can do this in three easy steps:

Configure jQuery dialog

The jQuery dialog has some nifty properties out of the box to handle things like, disabling the esc key, displaying the modal dialog on page load, along with the usual suspects: style, size, resizing. Here is what my call looks like, with our special properties highlighted in blue:

$(function() {
$("#registrationform").dialog({
height: 470,
width: 520,
resizable: false,
<span style="color: #0000ff;">autoOpen</span>: true,
<span style="color: #0000ff;">modal</span>: true,
<span style="color: #0000ff;">closeOnEscape</span>: false
});
});
1

<h2>Hide the dialog's x button</h2>
The dialog shows a x in the top right corner by default, and there are no properties to hide it. The best way I found is using some old fashioned CSS:

1
<style>
.ui-dialog .ui-dialog-titlebar-close { display: none; }
</style>

So that is all it takes to set the dialog to display on page load and prevent users from escaping out or closing the form. Next is sending the results back to the server, which is pretty simple using $.post.

Post back to the server and process results

First, you need to handle a button’s click event, and have some logic to process the result. I primarily develop in ASP.NET MVC, but you could very easily use this technique in PHP, Ruby, etc. Here is the function:

function Register() {
$.post("/Contact/RegisterGuest",
{
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val(),
Phone: $("#Phone").val()
},
function(data) {
Result = eval('(' + data + ')');

if (Result == "") {
$('#registrationform').dialog('close');
$("#registrationform").hide("fast");
$("#result").show("fast");
}
else {
$("#errorblock").html("<ul>" + Result + "</u>");
}
});
}

Breaking down the function, we’re posting to the RegisterGuest method for the Contact controller, with the FirstName, LastName, Email, and Phone fields, and processing the result. Typically I’ll return any errors in listitem tags, so an empty Result means no errors occurred on the server-side. If the Result variable is empty, we hide the dialog and show whatever was hidden. Otherwise we set the html value for a pre-defined div to be the error list.

, ,

TOP