I am to new .NET core using 2.2 version. I am trying to pass data to partial view with following code:
<partial name="_Emplyees" model="@Model.Employees" view-data="@new ViewDataDictionary(ViewData) { { "index", index }}"/>
but its giving syntax error. can someone guide how to pass data and use in partial view? Thanks in advance.
The issue is that you've got double quotes inside the view-data
attribute. You need to use single quotes around the attribute value.
<partial name="_Emplyees" model="Employees" view-data='@new ViewDataDictionary(ViewData) { { "index", index } }'/>
Also, @Model
is superfluous here, so I removed it.
You could pass the ViewData to partial view like below in ASP.Net Core MVC:
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.Partial View:
<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.Result:
Reference:
See Partial views in ASP.NET Core and Partial Tag Helper in ASP.NET Core .
<partial name="Shared/_ProductPartial.cshtml" for="Product">
<partial name="_ProductViewDataPartial" for="Product" view-data="ViewData">
@await Html.PartialAsync("_ProductPartial", product)
Note:
When a partial view is instantiated, it receives a copy of the parent's ViewData dictionary.
As per the documentation, When a partial view is instantiated, it receives a copy of the parent's ViewData dictionary. Updates made to the data within the partial view aren't persisted to the parent view. ViewData changes in a partial view are lost when the partial view returns.
Checkout the documentation here
For me I have simply created a partial view, accessed it inside another view and used ViewData directly inside it.
~/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" />
So without passing anything to partial view _PageTop, I can access parent's Title property directly using @ViewData["Title"].
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.