mvc aspx视图中的Model为null

时间:2016-09-21 07:25:15

标签: html asp.net-mvc

我是mvc的新手。我试图在我的“视图”中使用if else等条件,但它会在“Model.sayHello”中抛出一个对象引用错误。

<%@ 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()
    {
    }
}

为什么我的模型返回null?

1 个答案:

答案 0 :(得分:0)

您收到此错误,因为模型未在控制器方法中初始化。对于HttpGet控制器操作,您的模型应该在将其传递给view之前处于初始化状态。

声明你的控制器方法 -

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