Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass View Data to Partial View in Asp.net core?

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.

like image 849
abhisingh12 Avatar asked Oct 16 '19 18:10

abhisingh12


People also ask

How do you pass ViewData to partial view?

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.

How can we call a partial view in view of ASP NET core?

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.


2 Answers

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.

like image 87
Chris Pratt Avatar answered Oct 11 '22 03:10

Chris Pratt


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:

enter image description here

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

like image 40
Rena Avatar answered Oct 11 '22 03:10

Rena