Dynamically add options to dropdown list using jQuery

Filed in Html | jquery Leave a comment

This post is going to be a fun little exercise, and is a technique that used to carry some overhead (in terms of postbacks and viewstate) back in the day. The objective is to provide users with a dropdownlist containing pre-selected options – but allow them to add their own options, and persist those options back to the database.

Ingredients:
1 – dropdownlist
1 – textbox
2 – divs
3 – links
3 – jquery functions
1 – controller method

First we will create our html form. So far there is nothing controversial here, we are simply creating one div to hold the dropdownlist and the “add” link, and another div to hold the textbox and save/cancel links. To keep it simple, we are going to make this a color list:

<div id="FavoriteColorsList">
<select name="FavoriteColor" id="FavoriteColor" style="width:350px;">
<option value=""> Choose your favorite color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
<a href="#" onclick="AddCustomFavoriteColor(); return false;">add my color</a>
</div>

<div id="CustomFavoriteColorform" style="display:none;">
<input type="text" id="CustomFavoriteColor" name="customFavoriteColor" style="width:250px;">&nbsp;&nbsp;
<a href="#" onclick="SaveCustomFavoriteColor(); return false;">save</a>&nbsp;&nbsp;
<a href="#" onclick="CancelCustomFavoriteColor(); return false;">cancel</a>
</div>

The expected behavior is to show the dropdown initially, and then once the user clicks the “add my color” link, to hide the dropdown div, and then display the textbox div. To make this happen, we have three jquery functions that are called from the links:


function AddCustomFavoriteColor() {
    $("#FavoriteColorsList").hide("fast");
    $("#CustomFavoriteColorform").show("fast");
    $("#CustomFavoriteColor").val("");
    $("#CustomFavoriteColor").focus();
}

function CancelCustomFavoriteColor() {
    $("#CustomFavoriteColor").val("");
    $("#FavoriteColorsList").show("fast");
    $("#CustomFavoriteColorform").hide("fast");
}

function SaveCustomFavoriteColor() {
    var opt = "<option value='" + $("#CustomFavoriteColor").val() + "'>" + $("#CustomFavoriteColor").val() + "</option>";

    $('#FavoriteColor').append(opt)
    $("#FavoriteColor").val($("#CustomFavoriteColor").val());

    $.post("/[YOUR-CONTROLLER]/[YOUR-METHOD]", { FavoriteColor: $("#CustomFavoriteColor").val() },
        function(data) {
            $("#CustomFavoriteColor").val("");
            $("#FavoriteColorsList").show("fast");
            $("#CustomFavoriteColorform").hide("fast");
        });
}

The last part is the server-side code to persist the saved value to the database. That is where you need to make sure you have some level of security, ideally something greater than what citibank rolled out.

Below is a video clip of the code in action:

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:

,

How to configure AdSense for Parked Domains

Filed in Google 1 Comment

If you’re anything like me, you probably have about 100 domains registered, doing nothing but putting money in godaddy’s pocket. I’ve been playing around with AdSense, and found some great documentation which shows how to configure your parked domains to use google’s AdSense instead. Without further adieu, here are the steps:

AdSense for Domains

After logging into your AdSense account, click the “AdSense Setup” tab, then the “Get Ads” link, and finally, click the “AdSense for Domains” link.

Add your Domains

This one is pretty easy. Click the “Add new domains” link to reach the add domains page.

From here, Google gives you two options:

  1. Manually type in all the domains you want to park (up to 1500)
  2. Upload a CSV file containing your domains

Very Important: Make sure you select your language, and then click the “Add domain(s)” button.

Once you have added your domains, you need to make DNS changes to point all those domains to google. To pull this off, you need:

  • Your unique pub id
  • A record and CNAME values

Google gives you both, and appears on the next screen after you Add your domains:

Updating DNS Entries

I’m currently on godaddy, so all my screen shots are from my account. Google does have step-by-step for other hosts like enom, register.com, 1and1, network solutions, yahoo, etc.

Updating with godaddy is pretty easy, whether you have 1 domain or 1500. All you have to do is apply the changes to one domain, and then bulk copy the settings to the other domains.

Making CNAME and A record changes to initial domain

From your domain manager, select the initial domain you want to change, and then scroll to the “Total DNS” section and click the “Total DNS Control” link.

Once you see the screen containing all the A, CNAME, and MX settings, click the edit icon (paper with pencil) in the CNAME’s “www” row. When the following popup opens, change the “Points To Host Name” to be your unique pub id from the AdSense page.

Click the “Ok” button, and then click the “Add New A Record” button. When the popup window opens, the IP address should point to 216.239.32.21. Repeat that for the other three IP addresses:

  • 216.239.34.21
  • 216.239.36.21
  • 216.239.38.21

After adding all the IP addresses, now comes the fun part:

Bulk Copy DNS Settings

Godaddy actually makes this pretty easy. All you have to do is:

1. Click the “Copy” button, the following screen will pop up:


2. Check the box next to all the domains you want receiving AdSense.

3. Check each box BELOW the above popup (yeah, not the best UI choice) next to the new entries (all the A Record @ rows and the CNAMES www row):

4. Click the “Copy Records” button in the window listing all the domain names.

Hurry up and wait

After completing the domain registrar step, you just have to wait around for two things:

1. The DNS changes to propagate

2. Godaddy to approve your sites

When I did it for about 30 or so domains, the whole process took a total of 30 minutes, but your time may vary.

, ,

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);
        }

, ,

TOP