决定学习ASP.NET MVC,并立即陷入简单的困境。ASP.NET中的类似于用户控件的行为mvc
在Web窗体用户控件允许根据功能将应用程序分成组件,并促进重用。似乎部分视图应该在ASP.NET MVC中做类似的事情,但是我得到这个错误,或者每个可见页面都由单个控制器处理,并且不可能将某些页面部分委托给单独的控制器而无需硬编码这些控制器关系。
RenderAction可以呈现局部视图并在页面中插入结果HTML,但如果我们希望在用户单击此视图中的某个链接以及整个页面时刷新此视图,则需要所有局部视图链接引用父控制器?
例如:
首页\ Index.aspx的:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Home</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
...
<% Html.RenderAction("Index", "Posts"); %>
...
帖子\ Index.aspx的:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BlogEngine.Models.PostsViewModel>" %>
<% foreach(var item in Model.Posts){ %>
<p class="postMeta"><%: string.Format("{0} {1}", item.CreatedAt, item.CreatedBy) %></p>
<h1><%: item.Title %></h1>
<div><%: item.Content %></div>
<% } %>
<% if (Model.CurrentPage > 0){ %>
<%: Html.ActionLink("Newer posts", "Index", "Home", new { page=Model.CurrentPage - 1}, null) %>
<%} %>
<% if (Model.CurrentPage + 1 < Model.TotalPages) { %>
<%: Html.ActionLink("Older posts", "Index", "Home", new { page=Model.CurrentPage + 1}, null) %>
<% } %>
PostsController:
public class PostsController : Controller
{
private const int PostsPerPage = 2;
private readonly IPostRepository _postRepository;
public PostsController()
{
...
}
public ActionResult Index(int page = 0)
{
var model = new PostsViewModel();
int totalPages = 1;
model.CurrentPage = page;
model.Posts = _postRepository.GetPosts(page, PostsPerPage, out totalPages);
model.TotalPages = totalPages;
return PartialView(model);
}
}
有没有比这更好的方法?
您只需将所需 “反向链接” 的局部视图。 – queen3 2010-09-17 14:33:36