1

新しいMVC4プロジェクトがあります。

私の_Layout.cshtmlには、次のものがあります。

<div class="container maincontent">
        <div class="row">
            <div class="span2 hidden-phone">
                @*
            In here is a RenderSection featured. This is declared in a section tag in Views\Home\Index.cshtml. 
            If this is static text for the whole site, don't render a section, just add it in.
            You should also be able to use  @Html.Partial("_LoginPartial") for example. 
            This _LoginPartial will need to be a cshtml in the Shared Views folder. 
            *@

                @{ Html.RenderPartial("_NewsFeed"); }
            </div>
            <div class="span10">
                @RenderBody()
            </div>
        </div>
    </div>

私の部分的な見方は

<div class="row newsfeed">
NEWS FEED
@foreach (var item in ViewData["newsfeed"] as IEnumerable<NewsItem>)
{
    <div class="span2 newsfeeditem">
        <h3>@item.NewsTitle</h3>
        <p>@item.NewsContent</p>
        @Html.ActionLink("More", "NewsItem", "News", new {id=@item.Id}, null)
    </div>    
}    

部分ビューでデータ呼び出しを行う方法はありますか?現在、すべてのアクションについて、コントローラーで次のことを行う必要があります。

ViewData["newsfeed"] = _db.NewsItems.OrderByDescending(u => u.DateAdded).Where(u => u.IsLive == true).Take(4);
        return View(ViewData);

モデルをビューに渡すことができないので、モデルをビューに渡すと、行き詰まりがなくなります。

私は自分が何か間違ったことをしていることを知っていますが、何がどこにあるのかわかりません。

_layoutでレンダリング呼び出しを行い、次に部分ビューでデータを収集してからそれ自体をレンダリングできるようにしたいだけです。または、スティックの端が間違っていませんか?私はそれをascxのように使おうとしていると思います...

4

1 に答える 1

2

RenderPartialの使用からに切り替える必要がありRenderActionます。これにより、パイプラインを再度通過して、部分的なものと同じようにActionResultを生成できますが、サーバー側のコードを使用します。例えば:

@Html.RenderAction("Index", "NewsFeed");

次に、を作成し、アクションメソッドNewsFeedControllerを提供します。Index

public class NewsFeedController : Controller
{
     public ActionResult Index()
     {
          var modelData = _db.NewsItems.OrderByDescending(...);
          // Hook up or initialize _db here however you normally are doing it

          return PartialView(modelData);
     }
}

次に、Views / NewsFeed/Index.cshtmlの場所に通常のビューのようにCSHTMLを配置します。

于 2013-03-26T16:28:02.647 に答える