简体   繁体   中英

Passing a model with a Partial View

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.

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM