当我尝试在View中访问Model时出现Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

时间:2018-07-27 10:38:12

标签: c# asp.net asp.net-mvc-4

我在一个典型的地方遇到问题。 当我在View中访问模型或任何动态变量(通过ViewBag)时, 我收到了Microsoft.CSharp.RuntimeBinder.RuntimeBinderException。

示例 查看(View / Assignments / Assignments.cshtml):

@using DocMaster.Models
@model List<IGrouping<string, User>>
...
<ul class="tree">
  @foreach (var dep in Model)
  {
    <li class="close" name='open_close'>
      <span class="org">@dep</span>
      <ul>
        @foreach (var user in dep)
        {
          <li class="li_user" name="resp_add" id="@user.Id">
            <span class="user">@user.Surname @user.Name @user.Patronymic</span>
          </li>
        }
      </ul>
   </li>
  }
</ul>

控制器(Controllers / AssignmentController.cs):

public class AssignmentController : Controller
{
    private  PgDb db = new PgDb();

    [HttpGet]
    public ActionResult Assignments(Guid docId)
    {
        var departments = db.Users.OrderBy(x => x.Surname).GroupBy(x => x.Department.Name).ToList();

        return View(departments);
    }
}

StackTrace

Строка 76:                         <div class="dn" id="user_book03">
Строка 77:                             <ul class="tree">
Строка 78:                                 @foreach (var dep in Model)
Строка 79:                                 {
Строка 80:                                     <li class="close" name='open_close'>

Исходный файл: C:\Users\ruslan\source\repos\Documentics\DocMaster\Views\Assignment\Assignments.cshtml    Строка: 78 

Трассировка стека: 


[RuntimeBinderException: Не удается выполнить привязки исполняющей среды по нулевой ссылке]
   CallSite.Target(Closure , CallSite , Object ) +115
   System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) +629
   ASP._Page_Views_Assignment_Assignments_cshtml.Execute() in C:\Users\ruslan\source\repos\Documentics\DocMaster\Views\Assignment\Assignments.cshtml:78
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64

1 个答案:

答案 0 :(得分:0)

您确定

        var departments = db.Users.OrderBy(x => x.Surname).GroupBy(x => x.Department.Name).ToList();

返回一个值,因为错误坚持要求您在代码中的某处具有空引用,并且我假设这就是代码给出的地方。调试控制器方法,找出空引用在哪里。