简体   繁体   English

通过局部视图传递模型

[英]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". 到目前为止,我在共享视图文件夹“ _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? 如果从8个不同的屏幕调用此视图,则这些屏幕的8个控制器是否会调用以获取我的警报并进行格式化?

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 您可以在控制器内定义所需​​的操作,然后调用@Html.Action而不是@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. 如果您拥有传递给partial所需的所有数据,则可以使用@ Html.Partial并传递模型。

If on the other hand, you want the view you are embedding to get the data itself, then you would use Html.RenderAction 另一方面,如果您希望嵌入的视图获取数据本身,则可以使用Html.RenderAction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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