I have a partial view that fills a select option.
From another view, I need to call the previous partial view to display my <select> <option> />
component.
However, I need to call the partial view WITH the associated controller.
Note : I am using .NET Core 6.
Here is my Controller :
public async Task<IActionResult> getYearMonth()
{
var result = await _context.MonthlyConsumption.Select(t => new { t.Time.Year, t.Time.Month }).ToListAsync();
return PartialView(result);
}
And my PartialView :
@model IEnumerable<TestLogin.Models.MonthlyConsumption>
<select name="mois" id="mois">
@foreach(var item in Model){
<option value="@Html.DisplayFor(modelItem => item.Time)">@Html.DisplayFor(modelItem => item.Time)</option>
}
</select>
I want to call the Controller’s Action method of the Partial View
I tried using @Html.Action
, @Html.RenderAction
but I can't use it.
@Html.Action is not working because i am using .NET 6
And I don't know why @Html.RenderAction is not working : IHtmlHelper does not contain definition for RenderAction
.
I looked up why I was getting this error message. Some people say you have to import System.Web.Mvc
but I can't get it to import in .NET 6.
CodePudding user response:
@Html.RenderAction
and @Html.Action
are not available in Asp.Net Core, There are two methods can achieve what you want.
The First method is to use View Component
. It is a new feature in Asp.Net Core and is also the officially recommended method, More details you can refer to this link.
The Second method is to use ajax, you can use ajax to access action, Then in success method, you can use js to add this partial view to the main View.