For a project I need a dynamic way of loading partial views, preferably by jquery / ajax.
Here's the functionality I require:
- User enters form. A dropdownlist is shown and a generic partial view is rendered with some input controls.
- User selects a different value in the dropdown
- The partial view refreshes. Based on the value of the dropdown, it should load the partial view. Some values have custom views associated with them (I could name them with the primary key for instance), others don't. When there's no custom view; it should load the default. When there is one, it should of course load the custom one.
And this should all be ajaxified when possible.
I have read some things about dynamically loading partials, but I wanted to repost the complete case so I can find the best solution for this specific case.
Assuming you have a dropdown:
@Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
id = "myddl",
data_url = Url.Action("Foo", "SomeController")
}
)
you could subscribe for the .change()
event of this dropdown and send an AJAX request to a controller action which will return a partial and inject the result into the DOM:
<script type="text/javascript">
$(function() {
$('#myddl').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#result').load(url, { value: value })
});
});
</script>
And place a DIV tag where you want the partial view to render in your host view:
<div id="result"></div>
and inside the Foo action you could return a partial view:
public ActionResult Foo(string value)
{
SomeModel model = ...
return PartialView(model);
}
You should handle the value changed event of the combobox, get the Id selected, then use ajax to call a server action, passing the selected Id.
The server action will return the corresponding view. At client side you populate the returned view to a region on the page.
For example of the server side action:
public ActionResult GetView(int id)
{
switch (id)
{
case 1:
return View("View1", model1);
break;
case 2:
return View("View2", model2);
break;
default:
return View("Default", modelDefault);
}
}