1

我一直在问很多关于从数据库创建路线和创建新页面等等的问题,我有以下模型、控件和下面的视图:

模型

namespace LocApp.Models
{
    public class ContentManagement
    {
        public int id { get; set; }
        [Required]
        public string title { get; set; }
        public string content { get; set; }
    }
}

控制器

    public ViewResult Index(string title)
    {
        using (var db = new LocAppContext())
        {
            var content = (from c in db.Contents
                           where c.title == title
                           select c).ToList();

            return View(content);

        }
    }

查看(部分)

@model IEnumerable<LocApp.Models.ContentManagement>

@{
    foreach (var item in Model)
    {
       <h2>@item.title</h2>
        <p>@item.content</p> 
    }
}

*查看(完整)- 请注意,此代码调用 _Content 部分*

@model IEnumerable<LocApp.Models.ContentManagement>

@{
    ViewBag.Title = "Index";
}

@{
    if(HttpContext.Current.User.Identity.IsAuthenticated)
    {
        <h2>Content Manager</h2>

        Html.Partial("_ContentManager");
    }
    else
    {
        Html.Partial("_Content");
    }
}

当您访问 site.com/bla 时,模型已被处理并包含信息,但随后它“神奇地”重新加载,我打破了控制器和视图的指向以观察这种情况的发生。第二次模型为空,因此页面上不显示任何内容。

我的路线如下:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("favicon.ico");

        routes.MapRoute(
            "ContentManagement",
            "{title}",
            new { controller = "ContentManagement", action = "Index", title = UrlParameter.Optional }
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );


    }

更新

看起来问题很简单:索引正在获取标题,循环并获取内容,然后将其传递给应有的查看方式。但是在页面加载完成之前,它会再次循环,这次将 null 作为标题传递,从而加载一个空页面。

4

1 回答 1

-1

我看到的最大问题是您实际上并没有将模型传递给局部视图

@model IEnumerable<LocApp.Models.ContentManagement>

@{
    ViewBag.Title = "Index";
}

@{
    if(HttpContext.Current.User.Identity.IsAuthenticated)
    {
        <h2>Content Manager</h2>

        Html.Partial("_ContentManager", Model);
    }
    else
    {
        Html.Partial("_Content", Model);
    }
}
于 2013-04-25T18:57:24.447 回答