2016-09-21 70 views
0

我是mvc的新手。我試圖在我的「視圖」中使用像if else一樣的條件,但它在「Model.sayHello」中引發對象引用錯誤。模型在mvc aspx視圖中爲null

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<myMVC.Models.myMVCMaster>" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title></title> 
</head> 
<body> 
<div> 
    <% using (Html.BeginForm("Index", "myMaster", FormMethod.Post, new { id = "SubmitForm" })) 
     { %> 
    <%: Html.ValidationSummary(true)%> 
    <% if(Model.sayHello) { 
     <div>Hello world!</div> 
    <% } 
     } %> 
</body> 
</html> 

控制器:

public class myMasterController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index(myMVCMaster model) 
    {    
     model.InitializePage(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(myMVCMaster model, string Command) 
    { 
    } 
} 

型號:

public class myMVCMaster 
{ 
    private bool _sayHello = false; 
    [System.ComponentModel.DefaultValue(false)] 
    public bool sayHello{ get { return _sayHello; } set { _sayHello = value; } } 

    public void InitializePage() 
    { 
    } 
} 

爲什麼我的模型返回爲空?

+0

有你甚至配置項目中使用剃刀?視圖中的其他代碼('<%... %>')使用的是ASPX –

+0

您已經在這裏結合了兩種語法 –

+1

我認爲您的視圖不使用使用舊的aspx視圖引擎的剃鬚刀視圖引擎..所以請嘗試使用<% %>而不是@。 –

回答

0

您正在收到此錯誤,因爲該模型未在控制器方法中初始化。對於HttpGet控制器操作,您的模型在傳遞給view之前應處於初始化狀態。

聲明你的控制器的方法是這樣 -

[HttpGet] 
public ActionResult Index() 
{ 
    myMVCMaster model = new myMVCMaster(); 
    model.InitializePage(); 
    return View(model); 
}