我一直在询问有关从数据库创建路径和创建新页面等等的很多问题,我有以下模型,控件和下面的视图:
模型
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 partial *
@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作为标题传递,从而加载一个空页面。
答案 0 :(得分:-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);
}
}