这是我的控制器代码。第一种方法是在主页上显示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{
}
嗨,你有没有在你的视图中尝试RenderAction?用局部视图 – Matteo1010
在主视图中使用'@ {Html.RenderAction(“Sidebar”)'来渲染由'Sidebar()'方法返回的局部视图 –
这解释了所有的https://stackoverflow.com/questions/ 45647211/asp-net-mvc-5-how-to-call-a-function-in-view – Matteo1010