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;"> <a href="#" onclick="SaveCustomFavoriteColor(); return false;">save</a> <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:







