2010-03-15 36 views

回答

6

你可以使用Html.RenderAction

public class MyController 
{ 
    [ChildActionOnly] 
    public ActionResult Foo(int id) 
    { 
     var content = GetContentFromDatabase(id); 
     return Content(content, MediaTypeNames.Text.Html); 
    } 
} 

並且在視圖包括部分:

<%= Html.RenderAction("foo", "mycontroller", new { id = 5 }) %> 

備註:RenderAction是現在發佈的ASP.NET MVC 2 RTM的一部分。對於ASP.NET MVC 1,您可以查看包含此擴展方法的Futures程序集。

0

在您的視圖中,使用Html.RenderPartial函數。有幾個不同的用途:

您可以通過在模型中的部分觀點:<% Html.RenderPartial("partialName", model); %>

或者你可以在一個全新的ViewDataDictionary傳:<% Html.RenderPartial("partialName", viewData); %>

有關完整文檔,請參見here

編輯:(答案評論):

的你觀點的模式,我將包括數據部分。例如,我們在模型中假設你有:

List<Person> People; 

在你看來,你想通過對這些每一個迴路,並使用PartialView顯示細節:

<% foreach(var p in Model.People){ %> 
     <p> <% Html.RenderPartial("personPartial", p); %> </p> 
<%}%> 

現在,您PartialView可能看起來像:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Person>" %> 
<%=Model.PersonName%> 
+0

作爲模型,我會傳遞什麼? 可以說我想顯示不同段落的內容,如

[這裏的數據來自db其id = 5]

,

[這裏的數據來自db其id = 7]

等等。 – coure2011 2010-03-15 16:18:31

+0

我不想顯示所有在Model.People中,只是想顯示一些像5,8等id。 – coure2011 2010-03-15 17:11:31

+0

然後只將該項目添加到模型。我以列表爲例。關鍵是將對象本身添加到模型中,而不僅僅是它的ID。 – mlsteeves 2010-03-15 17:14:55