For a project I need a dynamic way of loading partial views, preferably by jquery / ajax.
Here's the functionality I require:
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.
The Partial View will be updated with the partial view returned from the child action. Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.
It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.
To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With