2014-11-24 70 views
0

我在我的MVC陛下控制器具有沿下面的行一對夫婦的方法:MVC - 顯示多個控制器結果在一個視圖中

public ActionResult _GetServiceStatus() 
{ 
... 
} 

public ActionResult _GetEventLogErrors() 
{ 
... 
} 

每種方法引用不同類類型我分別存儲在我的模型,服務和事件中。這些可以看到如下:

public class Service 
    { 
     public string Name { get; set; } 
     public string Status { get; set; } 
    } 

    public class Event 
    { 
     public string Source { get; set; } 
     public string EntryType { get; set; } 
     public string Message { get; set; } 
     public DateTime Date { get; set; } 
    } 

我想要做的是在單個視圖中顯示這些方法的結果。我已經爲服務檢查工作,結果正確顯示,但我無法找到如何添加事件結果。

下面我有什麼目前我的看法是:

@{ 
    ViewBag.Title = "Monitoring"; 
} 

@model IEnumerable<SystemMonitoringTool.Models.Monitoring.Service> 

<div style="width:25%"> 
    <span> 
     Services 
    </span> 
    <table id="services" style="border:solid; border-width:2px; width:100%"> 
     @foreach (var item in Model) { 
     <tr> 
      <td> 
       @Html.DisplayFor(model => item.Name) 
      </td> 
      <td> 
       @Html.DisplayFor(model => item.Status) 
      </td> 
     </tr>      
     } 
    </table> 
</div> 

有人可以幫助我找到一種方法,在同一個視圖中顯示這些並排?如果需要,將很樂意提供更多信息。

回答

3

兩個選項:

  1. 使用童工的行爲。而不是直接將這些單個控制器動作中的一個,而不是添加一個動作,如:

    public ActionResult Monitoring() 
    { 
        return View(); 
    } 
    

    你會注意到這個動作沒有做太多。這只是渲染一個視圖。然後,您需要將您的HTML服務/事件移至部分視圖。例如,_GetServiceStatus.cshtml_GetEventLogErrors.cshtml,其中每個的型號將分別爲您的ServiceEvent類型的集合。最後,在Monitoring.cshtml視圖(基於上面的動作名),你將添加:

    @Html.Action("_GetServiceStatus") 
    @Html.Action("_GetEventLogErrors") 
    

    這種觀點並不需要一個模型,因爲它直接與任何工作不。

  2. 使用封裝的兩個集合視圖模型:

    public class MonitoringViewModel 
    { 
        public List<Service> Services { get; set; } 
        public List<Event> Events { get; set; } 
    } 
    

    然後,你仍然需要一個統一的行動。但是在這裏,你將填充這兩個列表。基本上,你只可以移動你的兩個現有行動統一到一個:那

    public ActionResult Monitoring() 
    { 
        var model = new MonitoringViewModel 
        { 
         Services = /* code to retrieve services */, 
         Events = /* code to retrieve events */ 
        } 
        return View(model); 
    } 
    

    ,您可以通過每個列表迭代獨立建立自己的HTML:

    Monitoring.cshtml(再次,基於動作名稱)

    @model Namespace.To.MonitoringViewModel 
    
    ... 
    
    <table id="services" style="border:solid; border-width:2px; width:100%"> 
        @foreach (var item in Model.Services) { // notice the change here 
        <tr> 
         <td> 
          @Html.DisplayFor(model => item.Name) 
         </td> 
         <td> 
          @Html.DisplayFor(model => item.Status) 
         </td> 
        </tr>      
        } 
    </table> 
    
+0

大,感謝您的幫助。去了第二個選項,它的工作是一種享受! – jimminybob 2014-11-24 17:10:32

相關問題