決定學習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