2017-08-12 100 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 
相关问题