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.
Pass Data to Partial View using ViewBag/ViewData You can use ViewData / ViewBag to pass the information from the controller's action method to the View. ViewData uses ViewDataDictionary and ViewBag is just a wrapper around ViewData using dynamic feature.
Declare partial views In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.
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:
How to use view-data pass the data to partial view
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.0#access-data-from-partial-views
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With