【问题标题】:Return partial view within view返回视图内的局部视图
【发布时间】:2026-01-20 06:55:01
【问题描述】:

我有观点Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Add</h2>

<p>Begin building a question set by clicking the button below.</p>
<input type="button" value="Create" onclick="location.href='@Url.Action("Product", "Add")'" />

在我的 AddController 中调用 Product 操作:

public ActionResult Product()
{
   ViewBag.Partial = true;
   return PartialView("Product");
}

我想要实现的是:

当用户加载页面时,我的部分视图 (Product.cshtml) 中的内容是隐藏的,但是当他们单击“创建”按钮时,该按钮会在我的 AddController 中调用 Product 操作,然后我想加载Product.cshtml 对我的Index.cshtml 的部分视图,因此后者仍然具有其原始内容,但这次将Product.cshtml 注入其中。

目前,它只返回部分视图,而不是两个视图。

这在 MVC 中可以实现吗?

【问题讨论】:

  • 您有想要展示的产品列表吗?一种方法是使用 Product 的 EditorTemplate,因此 Product.cshtml
  • 您发布的代码没有这样做。它将用户发送到另一个视图。

标签: c# asp.net-mvc


【解决方案1】:

是的,基本上您需要的是通过 AJAX 调用获取您的 PartialView 并将其加载到您的页面中。用 jQuery 最容易做

您可以使用简单的 JavaScript 来做到这一点。

在按钮onclick 中输入加载函数的名称,例如onclick="partialLoad()"

在您的页面上添加div 和一些id,例如&lt;div id="loadFrame"&gt;&lt;/div&gt;

然后你的脚本:

function parialLoad() {
    $("#loadFrame").load("/Product");
}

【讨论】:

    【解决方案2】:

    我的建议如下。

    将您的 Products.cshtml 移动到 Views/Shared/EditorTemplates 或 DisplayTemplates 目录

    拥有一个您填充的 ​​ViewModel,其中包含您传入和传出视图的产品列表。

    因此:

    HomeController.cs

    public ActionResult Index()
    {
        var model = new ProductViewModel();
    
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Index(ProductViewModel model)
    {
        if (model == null)
        {
            model = new ProductViewModel();
        }
        if (model.Products == null)
        {
            model.Products = new List<Product>();
        }
        model.Products.Add(new Product { Name = "Some Product", Amount = model.Products.Count + 1});
    
        return View(model);
    }
    

    ProductViewModel.cs

    public class ProductViewModel
    {
        public List<Product> Products { get; set; }
    }
    

    Index.cshtml

    @model DynamicViewExample.Controllers.ProductViewModel
    @{
        ViewBag.Title = "About";
    }
    
    @using (Html.BeginForm())
    {
        <h2>Add</h2>
    
    
        @Html.DisplayFor(m => m.Products)
    
        <p>Begin building a question set by clicking the button below.</p>
        <input type="submit" value="Add Product" />
    }
    

    最后是 DisplayTemplate
    Product.cshtml

    @model DynamicViewExample.Models.Product
    <div>
        @Html.HiddenFor(x => x.Name)
        @Html.HiddenFor(x => x.Amount)
        @Html.DisplayFor(x => x.Name)
        @Html.DisplayFor(x => x.Amount)
    </div>
    

    我必须包含 HiddenFor 属性的原因是为了使 Products 集合能够填充,否则您将一直得到一个空集合。

    同样,这是一个显示模板,将返回以下结果

    添加

    一些产品 1
    部分产品2
    部分产品 3
    部分产品 4
    部分产品 5
    单击下面的按钮开始构建问题集。

    我希望这能引导你走向你希望去的方向

    祝你好运
    加维施耐德

    【讨论】:

      最近更新 更多