简体   繁体   中英

Dynamically add Views in ASP.NET MVC

I was originally developing a project for WPF, using MVVM, which had the benefit of allowing me to populate a list of views that I wanted available. Each view had a "Next" button that would progress to the next view in the list.

However, now I am trying to do the same in ASP.NET MVC. This is my first time using MVC, but I have an XML file, from which I need to generate this UI. These views, which are chosen from the script, also have components in them that are dynamic -- sometimes ViewA might need 3 "input views" nested in it, sometimes it might need 1.

I was achieving that before with ListBox , ItemsSource , and DataTemplate . So my question is this: how can I dynamically populate which views to display, and (more importantly) how can I dynamically fill those views with x number of control A, and y number of control B?

First off, a high-level overview of the project structure...

YourProjectName

  • Controllers
    • ProductController.cs
  • Models
    • ProductViewModel.cs
  • Views
    • _ProductPartial.cshtml
    • ListProducts.cshtml

ProductViewModel.cs

public class ProductViewModel
{
    public string Name { get; set; }
    public string Description { get; set; }
}

ProductController.cs

public class ProductController : Controller
{
    public ActionResult Index()
    {
        // Create your model (this could be anything...)
        var model = new List<ProductViewModel>
        {
            new ProductViewModel { Name = "Apple", Description = "A red apple" },
            new ProductViewModel { Name = "Orange", Description = "An orange orange" }
        };

        // Return the main view and your model
        return View("ListProducts", model);
    }    
}

_ProductPartial.cshtml

@model YourProjectName.Models.ProductViewModel

<h1>@Model.Name</h1>
<p>@Model.Description</p>

ListProducts.cshtml

@model System.Collections.Generic.List<YourProjectname.Models.ProductViewModel>

@foreach (var product in Model)
{
    Html.Partial("_ProductPartial", product)
}

Summary

Now if you request that controller action ( localhost/Product/Index or whatever it ends up being for you), the controller will create the model, render the parent view, and the parent view will render as many of the product partial views as necessary depending on the product model collection we defined in the controller. Views and partial views don't require models, but I imagine you will be using a model class of some sort to help you determine what/where/how many partial views to render in your parent views. This is about as basic as it gets but it should get you started in using partial views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM