When working in ASP.NET MVC, I have a partial view located inside "Views -> FirstController->_PartialView1.cshtml", I would like to call this partial view of "FirstController" from "SecondController", how can I call it in ASP.NET MVC?
The reason I am doing so is the HTML used is same, but with different data.
This is not a recommended way, but you can call Another Controller partial view like below
public PartialViewResult SomeActionName()
{
//some code here
return PartialView("~/Views/ControllerName/_PartialView.cshtml", YourModel);
}
or if PartialView in another Area
public PartialViewResult SomeActionName()
{
//some code here
return PartialView("~/Areas/AreaName/Views/ControllerName/_PartialView.cshtml", YourModel);
}
Best Practice is call PartialView from inside the view using Render partial or Partial
Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);
Or using
@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)
That's it.
Another best way is to place Partial View inside shared folder & call same partial View from different controller using Shared Folder.
So, basically you need to Create a Folder inside Views->Shared->SharePartialView ->_CommonPartialView.cshtml
And then call it from controller as mentioned above.
public PartialViewResult SomeActionName()
{
//some code here
return PartialView("~/Views/Shared/SharePartalView/_CommonPartialView.cshtml");
}
That's it.
This link may help you.
https://stackoverflow.com/questions/21089917/how-to-return-partial-view-of-another-controller-by-controller
You can call HTML.Action also from the view.
@Html.Action("Action", "Controller", new {id = model.id})
from the main view.
OR
You can directly also use RenderPartial
@Html.RenderPartial("~/Views/MainController/View.cshtml",Model)
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly