在视图中使用模型值时为空引用

时间:2013-05-23 21:08:55

标签: asp.net-mvc asp.net-mvc-4 nullreferenceexception

我在web.config

中声明我的值
 <appSettings>
    <add key="SystemName" value="RealState Premium" />
    <add key="SystemDescription" value="Sistema de Administração Imobiliário" />
  </appSettings>

配置模型:

    public class _Header
    {
        public string SystemName { get; set; }
        public string SystemDescription { get; set; }
    }

控制器:

    [AllowAnonymous]
    public ActionResult _Header()
    {
        HomeModels._Header headerModel = new HomeModels._Header();

        headerModel.SystemName = ConfigurationManager.AppSettings["SystemName"];
        headerModel.SystemDescription = ConfigurationManager.AppSettings["SystemDescription"];

        return PartialView(headerModel);
    }

以及最后一次,查看:

@using realstate.Models
@model HomeModels._Header

<div class="logo">
    <img src="~/Images/logo/logo.png" alt="Mercado de Imóveis" />
    <table class="sysTitleTbl">
        <tr>
            <td class="name">@Model.SystemName</td>
        </tr>
        <tr>
            <td class="description">@Model.SystemDescription</td>
        </tr>
    </table>
</div>

问题是我在@ Model.SystemName中获得了一个空引用 会出现什么问题?

2 个答案:

答案 0 :(得分:1)

将断点设置为这些代码行

headerModel.SystemName = ConfigurationManager.AppSettings["SystemName"];
headerModel.SystemDescription = ConfigurationManager.AppSettings["SystemDescription"];

看看它发生了什么

答案 1 :(得分:0)

确保在“/web.config”文件中设置appSettings节点,而不是“views / web.config”文件。另外,请确保它位于“配置”中。

示例:

<configuration>
    <appSettings>
        <add key="SystemName" value="RealState Premium" />
        <add key="SystemDescription" value="Sistema de Administração Imobiliário" />
    </appSettings>
</configuration>