MVC错误:访问模型数据时,对象引用未设置为对象实例

时间:2016-12-29 15:37:02

标签: asp.net-mvc-4

刚进入MVC,并遇到一些问题。我的观点是在尝试从新创建的模型中显示字符串时抛出上述错误。错误发生在@ Model.UserName

查看:

@using Nam.Models
@model Nam.Models.UserInfo
@{
    ViewBag.Title = "Operations";
}

<h2>Operations</h2>
<table border="2" cellpadding="2" cellspacing="2" width="30%" align="left">
<thead>
    <tr>
        <td colspan="2" align="center"><b>User Info</b></td>
    </tr>
</thead>
<tbody>
    <tr>
        <td><b>User:</b></td>
        <td>@Model.UserName</td>
    </tr>
</tbody>
</table>
<table border="2" cellspacing="2" cellpadding="2" width="40%" align="right">
<thead>
    <tr>
        <td colspan="2" align="center"><b>Main Info</b></td>
    </tr>
</thead>
</table>

控制器:

public ActionResult Index()
    {
        UserInfo UID = new UserInfo();
        {
            UID.UserName = "Name";
            UID.UserID = 0;
        }

        return View(UID);
    }

型号:

namespace Nam.Models
{
    public class UserInfo
    {
        public string UserName { get; set; }
        public int UserID { get; set; }
    }
}

WebConfig:

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="Nam" />
    <add namespace="DevExtreme.AspNet.Mvc" />
    <add namespace="Nam.Models"/>
  </namespaces>
</pages>

1 个答案:

答案 0 :(得分:0)

通过索引操作方法的模型未到达您的视图。 问题可能是您的相应视图未通过Index()方法呈现。

尝试在Index方法返回类型中添加视图名称。

return View("Operations",UID);

或者尝试使用Action Method的确切名称创建视图名称。(例如:Index.cshtml)并将您当前的视图代码粘贴到Index.cshtml中。