如何在Asp.net core中将视图数据传递给部分视图?

14

我是使用.NET Core 2.2版本的新手。我试图使用以下代码将数据传递给部分视图:

 <partial name="_Emplyees" model="@Model.Employees" view-data="@new ViewDataDictionary(ViewData) { { "index", index }}"/>

但是它正在产生语法错误。 有人可以指导如何传递数据并在部分视图中使用吗?提前致谢。


在Core 2.1至少到3.1中,有三种方法可以将视图数据传递给部分视图。使用Partial标签助手的formodelview-data属性。文档位于https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/partial-tag-helper?view=aspnetcore-3.1。 - Theophilus
4个回答

16
问题在于你在 view-data 属性内使用了双引号。你需要在属性值周围使用单引号。
<partial name="_Emplyees" model="Employees" view-data='@new ViewDataDictionary(ViewData) { { "index", index } }'/>

同时,这里的@Model是多余的,所以我将其删除。


13
在ASP.Net Core MVC中,您可以通过以下方式将ViewData传递给分部视图:
1. Model:
public class TestModel
{
    public string Employees { get; set; }
}

2.View(Create.cshtml):

@model TestModel
@{ 
    ViewData["index"] = true;
}
<partial name="_Emplyees" model="@Model" view-data="ViewData" />

3.局部视图:

<h3>Index: @ViewData["index"]</h3>
@model TestModel

@if ((bool)ViewData["index"])
{
    @Model.Employees
}
else
{
    <input asp-for="Employees" type="number" class="form-control" />
}

4.Controller:

public IActionResult Create()
{
    var testmodel = new TestModel() { Employees = "aaa" };
    return View(testmodel);
}

5.结果:

在这里输入图像描述

参考:

如何使用视图数据将数据传递到部分视图

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.0#access-data-from-partial-views


1
根据文档,当部分视图被实例化时,它会接收父视图的 ViewData 字典的副本。在部分视图中对数据所做的更新不会持久保存到父视图中。部分视图中的 ViewData 更改在部分视图返回时会丢失。
请查看文档 here 对于我来说,我只是创建了一个部分视图,在另一个视图中访问它并直接在其中使用 ViewData。

~/Views/Shared/_PageTop.cshtml

<a asp-controller="Home" asp-action="Index">Go Back</a>
<h1>@ViewData["Title"]</h1>

~/Views/Create.cshtml

@{
    ViewData["Title"] = "Create";
}
<partial name="_PageTop" />

所以在不将任何内容传递给局部视图_PageTop的情况下,我可以直接使用@ViewData["Title"]访问父级的Title属性。

1

请查看ASP.NET Core中的部分视图ASP.NET Core中的部分标签助手

<partial name="Shared/_ProductPartial.cshtml" for="Product">

<partial name="_ProductViewDataPartial" for="Product" view-data="ViewData">

@await Html.PartialAsync("_ProductPartial", product)

注意:
当部分视图实例化时,它会接收父视图 ViewData 字典的副本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接