@{
ViewBag.Title = "dynamicDropdown";
}
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />
<h2>Dynamic Dropdown using Jquery</h2>
<div id="div_cntr">
</div>
<script type="text/javascript">
$(function () {
//get the list of items
var deliverydrpDown = @Html.Raw(Json.Encode(@ViewBag.Fruits));
var dd1 = document.createElement("select");
dd1.name = "dynmcdrp_fruits";
dd1.id = "dynmcdrp_fruits";
$.each(deliverydrpDown,function(index,item)
{
//alert(item.Text);
dd1.options[dd1.length] = new Option(item.Text, item.Text);
});
//for dropdown onchange event
dd1.onchange = function() {
var drp = document.getElementById('dynmcdrp_fruits');
var selValue = drp.options[drp.selectedIndex].value;
customDialog("Information","Selected fruit is:- "+selValue);
};
//to set the selected item
//for (var i = 0; i < dd1.options.length; i++) {
// if (dd1.options[i].text == text) {
// dd1.selectedIndex = i;
// break;
// }
//}
$('#div_cntr').append(dd1);
});
//jquery custom dialog box to display exception
function customDialog(headerValue, message) {
//remove the existing div
var divs = $('body').find('div[id="div_customDialog"]');
$.each(divs, function (index, divItem) {
$(divItem).remove();
});
//add new div
$('body').append('<div id="div_customDialog"></div>');
$('#div_customDialog').html(message);
$('#div_customDialog').dialog({
draggable: true,
modal: true,
resizable: false,
width: 'auto',
title: headerValue,
minHeight: 75,
buttons: {
OK: function () {
$(this).dialog('close');
$(this).dialog('destroy');
}
}
});
$('#div_customDialog').dialog('open');
}
</script>
Controller:-
public ActionResult dynamicDropdown()
{
List<SelectListItem> fruits = new List<SelectListItem>();
fruits.Add(new SelectListItem { Text = "Apple", Value = "Apple" });
fruits.Add(new SelectListItem { Text = "Orange", Value = "Orange" });
fruits.Add(new SelectListItem { Text = "Mango", Value = "Mango" });
ViewBag.Fruits = fruits;
return View();
}
No comments:
Post a Comment