Reputation: 4854
I have a view that looks somewhat similar to this
<% using (Html.BeginForm()) {%>
<%= Html.DropDownList("Category") %>
<%= Html.DropDownList("SubCategory") %>
<input type="submit" value="Print" />
<%= Html.ActionLink("Cancel", "Index") %>
<% } %>
I was wondering if anyone knew how i could load the subcategory based on the selected Category? In webforms i'd just use the autopostback event to do this, but i'm a bit confused on how to do this using the mvc framework.
Thanks in advance
Upvotes: 1
Views: 2060
Reputation: 24882
transform your view like this:
<% using (Html.BeginForm()) {%>
<%= Html.DropDownList("Category", Model.SelectList, new {onchange = "actualize(this);"}) %>
<div id="selectdiv">
<% Html.RenderPartial("SubCategories"); %>
</div>
<input type="submit" value="Print" />
<%= Html.ActionLink("Cancel", "Index") %>
<% } %>
<script type="text/javascript">
function actualize(obj)
{
$.ajax({
url: url,
async: true,
type: 'POST',
data: { id: obj.value },
dataType: 'text',
success: function(data) { $("#selectdiv").html(data); },
error: function() {
console.log('Erreur');
}
});
}
</script>
create a control called SubCategories.aspx and include in it:
<%= Html.DropDownList("SubCategory",Model.SelectList) %>
create a Model class
public class MyModel
{
public SelectList SelectList {get;set;}
}
create a controller action
public ActionResult SubCategories(int id)
{
MyModel model = new MyModel();
model.SelectList = new SelectList(YourRepository.GetSubCategories(id),"Id","Name");
return View(model);
}
Upvotes: 2
Reputation: 22770
Place the dropdown list within a PartialView. Then when you post back do a return PartialView("viewName", model). Then in the return of your jQuery simply replace the partial view with the new html that is returned.
So you're view;
<div id="myPartialView">
<% Html.PartialView("PartialViewName", model); %>
</div>
Then your jQuery does something like
$('#myPartialView').html = retHtml;
Your C#
return PartialView("PartialViewName", model);
Untested but that's the approach i think you want to take.
Upvotes: 1