我有一個頁面包含一個Chart對象,我用它作爲ASP.NET MVC中的默認路徑。當我運行應用程序時,由於空引用,我得到一個異常。如果我使用控制器和明確給出的操作的URL,一切正常。爲什麼在ASP.NET MVC中使用默認路由時模型爲空?
這裏是爲了顯示我的意思的代碼...
在的RegisterRoutes:
routes.MapRoute("Default", "{controller}/{action}", new { controller = "Dashboard", action = "Index" });
DashboardModel.cs:
public class DashboardModel
{
public Chart MyChart { get; set; }
}
DashboardController.cs
public ActionResult Index()
{
Chart chart = CreateChart();
DashboardModel dm = new DashboardModel();
dm.MyChart = chart;
return View(dm);
}
Index.asp X
<% chartPanel.Controls.Add(Model.MyChart); %>
<asp:Panel ID="chartPanel" runat="server"></asp:Panel>
啓動從調試器應用程序與所述URL http://localhost:2313/導致NullReferenceExcpetion上上面的Index.aspx給出的第一行。如果我在瀏覽器中放入http://localhost:2313/Dashboard/Index,圖表會正確顯示。我在Index()操作中設置了一個斷點,它創建了一個有效的模型和圖表,並且在發生異常之前只觸發一次斷點。
爲什麼模型爲null?每當我的行動方法被調用時,應該創建它。必須有更多的事情發生在我不瞭解的默認路由上。
在這兩種情況下,它都擊中了你的斷點,對嗎? CreateChart()中是否有檢查URL或路徑信息的內容? –
有可能chartPanel或chartPanel.Controls爲null與模型? – Steven
@Smashd,是的,我的斷點在這兩種情況下都會發生。 CreateChart沒有檢查URL,它只是從存儲庫獲取數據,然後在數據庫中執行存儲過程。 –