2013-04-25 39 views
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作爲標題,從而加載一個空白頁面。

+0

在你的代碼看起來沒有什麼不正確。觀看小提琴手的請求,看看發生了什麼。 – BNL 2013-04-25 17:52:51

+0

這是EF代碼優先嗎? linq查詢是否返回視圖的正確類型?列表不是列表。我想你會發現它是後者。 – BNL 2013-04-25 17:56:08

+0

你發佈的內容沒有錯。任何JavaScript調用'window.location.reload'或類似的,可能會被意外解僱?您的視圖或佈局中的任何AJAX調用? – 2013-04-25 18:03:22

回答

-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); 
    } 
} 
+0

這不是必需的。部分視圖與他們父母的模型是固有的,至少當模型類型與他們在這裏相同時。 http://stackoverflow.com/questions/13431056/in-mvc-do-partial-views-inherit-the-models-of-their-parent-views這個問題不是最好的,但我只是驗證了我的PC。 – BNL 2013-04-25 19:18:45

+0

正確 - 但正如答案中所述,這不是好的做法。鑑於OP有問題,這將是我首先開始的地方。 – Tommy 2013-04-25 19:24:10

+0

這不是問題。該模型正在通過 – TheWebs 2013-04-25 19:55:25