Reputation: 18734
I want to show a view on some of my forms, which shows a list of alerts, read from a database table. I think I need to use a partial view - but haven't used one.
So far, I created a partial view in my shared views folder called "_Alerts.cshtml".
In that file, at the moment, I simply have:
@{
Layout = null;
}
This is a shared view.
This is just me trying to display something.
And then, on my existing page, on which I want to display the alerts, I have this section of code:
@if (User.Identity.IsAuthenticated)
{
<div class="row">
@Html.Partial("~/Views/Shared/_Alerts.cshtml", null)
</div>
}
This works. However, my understanding is not right. At the moment, I pass no model to it. Is there no controller for the partial view? At the moment, I need to create a controller method - somewhere - that gets me a list of alerts from my data service, and then I want to format that and present it in the partial view. But I am unsure where the controller methods go. If this view is called from 8 different screens, would the 8 controllers for these screens have a call to get my alerts, and format them?
Seems like a lot of duplication.
Upvotes: 1
Views: 168
Reputation: 9901
If you have all the data you need to pass into the partial, then you can use the @Html.Partial and pass in the model.
If on the other hand, you want the view you are embedding to get the data itself, then you would use Html.RenderAction
Upvotes: 1
Reputation: 17680
They need not be duplication.
You can define the action you want inside a controller and call @Html.Action
instead of @Html.Partial
Inside you action you can return a partial view.
public class AlertsController : Controller
{
public ActionResult Show()
{
var model = GetModel();//decide where this will come from.
return PartialView("~/Views/Shared/_Alerts.cshtml",model);
}
}
In your layout view or wherever you need to use it. you can simply call it as below.
@Html.Action("Show","Alerts")
Upvotes: 1