Refreshing A Dropdownlist After Elements Have Been Reset
i have an asp.net mvc 2 application, and have some jquery that defines behaviour of two dropdownlists. When one changes, the other is populated with filtered data. After much furor
Solution 1:
Try this:
$(function () {
$.fn.loadSelect = function (data) {
returnthis.each(function () {
this.options.length = 0;
var select = this;
$.each(data, function (index, itemData) {
var option = newOption(itemData.Text, itemData.Value);
$(select).append(option);
});
});
};
});
Notice that we need to capture this
in the outer foreach because in the inner it no longer points to the select
element.
Full working example:
Model:
publicclassItem
{
publicint Value { get; set; }
publicstring Text { get; set; }
}
publicclassMyViewModel
{
publicint? SelectedCompanyId { get; set; }
publicint? SelectedFieldOfficeId { get; set; }
public IEnumerable<Item> Companies { get; set; }
public IEnumerable<Item> FieldOffices { get; set; }
}
Controller:
[HandleError]
publicclassHomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Companies = Enumerable.Range(1, 5).Select(i => new Item
{
Value = i,
Text = "Company " + i
}),
FieldOffices = Enumerable.Empty<Item>()
};
return View(model);
}
public ActionResult FilterFieldOffices(int companyId)
{
return Json(Enumerable.Range(1, 3).Select(i => new Item
{
Value = i,
Text = "Field offfice " + i
}));
}
}
View:
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery-1.4.1.js") %>"></script>
<scripttype="text/javascript">
$(function () {
$('#cid').change(function () {
var coid = $(this).val();
$.post('<%= Url.Action("FilterFieldOffices") %>', { companyId: coid }, function (data) {
$('#foid').loadSelect(data);
});
});
});
$(function () {
$.fn.loadSelect = function (data) {
returnthis.each(function () {
this.options.length = 0;
var select = this;
$.each(data, function (index, itemData) {
var option = newOption(itemData.Text, itemData.Value);
$(select).append(option);
});
});
};
});
</script>
<% using (Html.BeginForm()) { %>
<%: Html.DropDownListFor(x => x.SelectedCompanyId, newSelectList(Model.Companies, "Value", "Text"), new { id = "cid" })%>
<%: Html.DropDownListFor(x => x.SelectedFieldOfficeId, newSelectList(Model.FieldOffices, "Value", "Text"), new { id = "foid" })%>
<inputtype="submit"value="OK" />
<% } %>
Post a Comment for "Refreshing A Dropdownlist After Elements Have Been Reset"