I want to display a dropdownbox on my MVC3 razor application from where user can select category and based on his selection i want to display subcategories which are checkbox so user can select multiple subcategories.
Can anyone help me how to get this?
Below is my json that i received from the web-service and and I deserialized that to the object, so how can i assign that object to two different list category(dropdown) and subcategory (check-boxes)?
JSON:
{
"Code":0,
"Status":"Done",
"Categories":[
{
"ID":1,
"Name":"Eat",
"Subcategories":[
{"Flag":false,"ID":100,"Name":"Food"},
{"Flag":false,"ID":101,"Name":"Fast Food"},
{"Flag":false,"ID":102,"Name":"Other"}
]
},
{
"ID":2,
"Name":"Entertainment",
"Subcategories":[
{"Flag":false,"ID":100,"Name":"All"},
{"Flag":false,"ID":101,"Name":"Movie"},
{"Flag":false,"ID":102,"Name":"Other"}
]
},
}
]
}
Entity:
public class MyData
{
public int Code { get; set; }
public string Status { get; set; }
public List<Category> Categories { get; set; }
}
public class Category
{
public string Name { get; set; }
public int ID { get; set; }
public List<Subcategory> Subcategories { get; set; }
}
public class Subcategory
{
public string Name { get; set; }
public int ID { get; set; }
public bool Flag { get; set; }
}
You could use AJAX. subscribe to the change event of the dropdownlist and trigger an AJAX request to a controller action passing along the selected category. The action will query the database for corresponding subcategories and return a partial view with corresponding checkboxes which will be injected into the DOM.
So let's suppose that you already have a dropdownlist for the categories in your view:
@Html.DropDownListFor(
x => x.CategoryId,
Model.Categories,
new {
id = "categories",
data_subcategoriesurl = Url.Action("subcategories", "somecontroller")
}
)
and some div which will contain the subcategories somewhere on the page:
<div id="subcategories">
@Html.EditorFor(x => x.SubCategories, "SubCategories")
</div>
and you could then have a SubCategories.cshtml
partial which will render the list of checkboxes:
@model IList<CategoryViewModel>
@{
// we change the HTML field prefix so that input elements
// such as checkboxes have correct names in order to be able
// to POST the values back
ViewData.TemplateInfo.HtmlFieldPrefix = "SubCategories";
}
@for (var i = 0; i < Model.Count; i++)
{
<div>
@Html.LabelFor(x => x[i].IsSelected, Model.CategoryName)
@Html.CheckBoxFor(x => x[i].IsSelected)
</div>
}
Now you could subscribe to the change event of the dropdown in a separate javascript file:
$(function() {
$('#categories').change(function() {
var subcategoriesUrl = $(this).data('subcategoriesurl');
var selectedCategoryId = $(this).val();
$('#subcategories').load(subcategoriesUrl, { id: selectedCategoryId });
});
});
and finally the SubCategories
action which will be invoked with AJAX:
public ActionResult SubCategories(int? id)
{
var subCategories = Repository.GetSubCategories(id);
return View(subCategories);
}