Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load Partial Views

How can i dynamically load a Partial View?

I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.

like image 866
Hélder Gonçalves Avatar asked Jul 03 '12 14:07

Hélder Gonçalves


People also ask

How do I load a partial view in a div?

In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

How do I return multiple partial views from a controller?

You can only return one value from a function so you can't return multiple partials from one action method. If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel.

When should partial views be used?

Partial views are an effective way to: Break up large markup files into smaller components. In a large, complex markup file composed of several logical pieces, there's an advantage to working with each piece isolated into a partial view.


1 Answers

Use jQuery's $.load() with a controller action that returns a partial view.
For example:

HTML

<script type="text/javascript"> $(document).ready(function() {     $("#yourselect").onchange(function()     {         // Home is your controller, Index is your action name         $("#yourdiv").load("@Url.Action("Index","Home")", { 'id' : '123' },                                          function (response, status, xhr)         {             if (status == "error")             {                 alert("An error occurred while loading the results.");             }         });     }); }); </script>  <div id="yourdiv"> </div> 

Controller

public virtual ActionResult Index(string id) {     var myModel = GetSomeData();     return Partial(myModel); } 

View

@model IEnumerable<YourObjects>  @if (Model == null || Model.Count() == 0) {     <p>No results found</p> } else {     <ul>     @foreach (YourObjects myobject in Model)     {         <li>@myObject.Name</li>     }     </ul> } 
like image 54
Chris S Avatar answered Oct 18 '22 12:10

Chris S