2017-08-12 103 views
0

這是我的控制器代碼。第一種方法是在主頁上顯示5個帖子。如何從家庭控制器向index.cshtml查看多個動作結果

第二種方法是在邊欄中顯示最近的帖子。

如何鏈接它以顯示在已顯示索引操作的帖子的視圖中?

控制器:

namespace ThelmaBlog.Controllers 
{ 
    public class HomeController : Controller 
    { 
     private ApplicationDbContext db = new ApplicationDbContext(); 
     public ActionResult Index() 
     { 
      var posts = db.Posts.Include(p => p.Author).OrderByDescending(p => p.Date).Take(3); 

      return View(posts.ToList()); 
     } 

     public ActionResult Sidebar() 
     { 
      var PostsTop5 = db.Posts.Include(path => path.Author).OrderByDescending(p => p.Date).Take(3); 

      return View(PostsTop5.ToList()); 
     } 

    } 
} 

查看:

@{ 
    ViewBag.Title = "Home Page"; 
} 

@model List<ThelmaBlog.Models.Post> 

@foreach (var post in Model) 
{ 
    <div class="row"> 
     <div class="post col-md-6"> 
      <h2 class="title">@post.Title</h2> 
      <div class="about"> 
       Posted on <i>@post.Date</i> 
       @if (post.Author != null) 
       { 
        @:by <i>@(post.Author.FullName + " (" + post.Author.UserName + ")")</i> 
      } 
      </div> 
      <div> 
       @Html.Raw(HttpUtility.HtmlDecode(post.Body)) 
      </div> 

     </div> 
    </div> 
} 

@section Sidebar{ 



} 
+0

嗨,你有沒有在你的視圖中嘗試RenderAction?用局部視圖 – Matteo1010

+0

在主視圖中使用'@ {Html.RenderAction(「Sidebar」)'來渲染由'Sidebar()'方法返回的局部視圖 –

+0

這解釋了所有的https://stackoverflow.com/questions/ 45647211/asp-net-mvc-5-how-to-call-a-function-in-view – Matteo1010

回答

0

變更側欄操作,以便它返回一個局部視圖:

public ActionResult Sidebar() 
{ 
    var PostsTop5 = db.Posts.Include(path => path.Author).OrderByDescending(p => p.Date).Take(3); 

    return PartialView("_Posts", PostsTop5.ToList()); 
} 

然後,創建一個局部視圖,叫_Posts.cshtml,用下面的代碼:

@model List<ThelmaBlog.Models.Post> 

@foreach (var post in Model) 
{ 
    <div class="row"> 
     <div class="post col-md-6"> 
      <h2 class="title">@post.Title</h2> 
      <div class="about"> 
       Posted on <i>@post.Date</i> 
       @if (post.Author != null) 
       { 
        @:by <i>@(post.Author.FullName + " (" + post.Author.UserName + ")")</i> 
      } 
      </div> 
      <div> 
       @Html.Raw(HttpUtility.HtmlDecode(post.Body)) 
      </div> 

     </div> 
    </div> 
} 

最後,改變你的索引視圖此:

@model List<ThelmaBlog.Models.Post> 

@{ 
    ViewBag.Title = "Home Page"; 
} 

@Html.Partial("_Posts", Model) 


@section Sidebar{ 
    @Html.Action("Sidebar", "Home") 
} 

順便說一句,您的任何操作都不會返回您在帖子中描述的內容。他們都返回完全相同的東西,這是前3名(而不是前5名)。

+1

「順便說一句,你的行爲都不會返回你在帖子中描述的內容,它們都返回完全相同的東西,這是前3名職位(不是前5名)。「發佈後我看到了。非常感謝 – Frankofoedu

0

sidebar內容添加到新的partialview,然後呈現指數這個局部視圖

@Html.Action("sidebar") // in your index page 
相關問題