【问题标题】:Shared partial view共享局部视图
【发布时间】:2014-05-29 11:42:54
【问题描述】:

在主页(HomeController,视图索引)上显示来自其他模型(新闻)的最后一条新闻的最佳方式是什么?

我在共享视图目录中创建了部分视图,它看起来是这样的:

   @model IEnumerable<MyApp.Models.News>

     @foreach (var item in Model.Where(x => x.IsActive ==
     true).OrderByDescending(x => x.DateCreated).Take(2))  {
         <li>
             @Html.ActionLink(item.DateCreated.ToString(), "Details", "News", new { id = item.NewsId})
             <p>@item.Content</p>
         </li>
 }

但是这样我会出错:

 An exception of type 'System.ArgumentNullException' occurred in
 System.Core.dll but was not handled in user code

模型不为空,我的数据库中有两个“活动”记录,该模型的索引文件也是正确的,但我不知道如何将这个部分呈现到我的索引主页...(现在我在 HomeController 的 Index.cshtml 视图中 @Html.Partial("_LatestNews"))

感谢您提前提供任何帮助。

【问题讨论】:

  • 我需要一些操作来呈现这样的局部视图吗?
  • 你打电话的地方,型号类型必须像 MyApp.Models.News chk

标签: asp.net-mvc model partial-views


【解决方案1】:

您需要像这样将模型传递给局部;

@Html.Partial("_LatestNews", Model.News))

【讨论】:

    【解决方案2】:

    您的部分视图期望您错过通过的 IEnumerable,它应该有这样的内容。

    @Html.Partial("_LatestNews", new IEnumerable<MyApp.Models.News>)
    

    但是,在这种情况下,我宁愿遵循。

    布局视图页面

    最新消息

    <script>
        $(function () {
            $("#content").html("Loading...");
            //Use setTimeout if you want to keep update or call LoadPartialView() directly.
            setTimeout(function () { LoadPartialView(); }, 5000);
        });
        function LoadPartialView() {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetNews", "Home")',
                dataType: "html",
                success: function (data) {
                    $("#content").empty();
                    $("#content").html(data);
                    $("#content").fadeIn('slow');
                },
                error: function (data) {
                    $("#content").empty();
                }
            });
        };
    </script>
    

    控制器

        [HttpPost]
        public ActionResult GetNews()
        {
            List<MyApp.Models.News> model = db.GetNews();
    
            return PartialView("_LatestNews", model);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多