Populating second DropDownList based on the selected value of first DropDownList in MVC2
I had the same problem as shown in this question so I tried his solution, but I couldn't make it work, probably because of my tiny knowledge of jquery and javascript. When I debug it in Firebug, I saw that it breaks at line:
$.post('<%: ResolveUrl("~/Home/GetSubcategories/")%>' + $("#ddlCats > option:selected").attr("value"), function (data) {
I have a correct action, and it should accept $("#ddlCats > option:selected").attr("value")
as parameter, but it never invoke that action, so it never returns JSON data, so it never populate second DDL. What am I doing wrong? Am I missing something?
Here is my model:
public class DdlModel
{
public lo开发者_StackOverflow中文版ng Id { get; set; }
public string Name { get; set; }
}
Here is controller:
public class HomeController : Controller
{
public ActionResult Index()
{
List<DdlModel> cats = DB.Category.FindCategories();
SelectList ddlCats = new SelectList(cats, "Id", "Name", cats[0].Name);
ViewData["ddlCats"] = ddlCats;
return View();
}
[HttpPost]
public JsonResult GetSubcategories(long catId)
{
var subCat = DB.Subcategory.FindSubcategories(catId);
return Json(subCat);
}
}
Here is my View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$('#ddlCats').change(function () {
$.ajaxSetup({ cache: false });
var selectedItem = $(this).val();
if (selectedItem == "" || selectedItem == 0) {
//Do nothing or hide...?
} else {
$.post('<%: ResolveUrl("~/Home/GetSubcategories/")%>' + $("#ddlCats > option:selected").attr("value"), function (data) {
var items = "";
$.each(data, function (i, data) {
items += "<option value='" + data.ID + "'>" + data.Name + "</option>";
});
$("#ddlsubCats").html(items);
$("#ddlsubCats").removeAttr('disabled');
});
}
});
});
</script>
<div>
<div>
<h2>
Choose category:
</h2>
<%:Html.DropDownList("ddlCats", (SelectList) ViewData["ddlCats"]) %>
</div>
<div>
<h2>
and subcategory:
</h2>
<select id="ddlsubCats" name="ddlsubCats" disabled="disabled">
</select>
</div>
</div>
</asp:Content>
I'm using: jquery-1.5.1.min.js and jquery-ui-1.8.11.custom.min.js.
Many thanks for any advice.
Try like this:
// TODO: make sure that the selectedItem variable represents a valid integer
// as the GetSubcategories expects it as argument:
var selectedItem = $(this).val();
if (selectedItem == "" || selectedItem == 0) {
//Do nothing or hide...?
} else {
var url = '<%= Url.Action("GetSubcategories", "Home") %>';
$.post(url, { catId: selectedItem }, function (data) {
...
});
}
Note that the GetSubcategories
expects a parameter called catId
which must be a valid 64 bit integer.
精彩评论