在ASP中动态添加视图.净MVC

本文关键字:视图 MVC 添加 动态 ASP | 更新日期: 2023-09-27 18:11:22

我最初使用MVVM为WPF开发一个项目,它的好处是允许我填充我想要的视图列表。每个视图都有一个"Next"按钮,可以跳转到列表中的下一个视图。

然而,现在我试图在ASP中做同样的事情。净MVC。这是我第一次使用MVC,但是我有一个XML文件,我需要从中生成这个UI。这些从脚本中选择的视图中也有动态组件——有时ViewA可能需要3个"输入视图"嵌套在其中,有时可能需要1个。

我之前用ListBox, ItemsSourceDataTemplate实现了这一点。所以我的问题是:我怎么能动态地填充哪些视图显示,(更重要的是)我怎么能动态地填充这些视图与x数量的控件A,和y数量的控件B?

在ASP中动态添加视图.净MVC

首先,项目结构的高级概述…

YourProjectName

  • 控制器
    • ProductController.cs
  • 模型
    • ProductViewModel.cs
  • 视图
    • _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)
}

现在如果你请求控制器动作(localhost/Product/Index或任何它最终为你),控制器将创建模型,呈现父视图,父视图将根据我们在控制器中定义的产品模型集合呈现尽可能多的产品部分视图。视图和分部视图不需要模型,但我想你会使用某种类型的模型类来帮助你决定在父视图中渲染什么/在哪里/有多少分部视图。这是最基本的,但它应该让你开始使用部分视图。