2015-06-22 42 views
0

我有以下的MVCNullReference錯誤而assiging在MVC視圖(剃刀)Modeltype值

型號:

Public Class Employee 
    Public Property EmployeeID As Integer 
End Class 

控制器:

Namespace Controllers 
    Public Class EmployeeController 
     Inherits Controller 
     Function Details() As ActionResult 
      Dim employee As Employee 
      employee = New Employee 
      employee.EmployeeID = 101 
      Return View() 
     End Function 
    End Class 
End Namespace 

查看:

@ModelType MVCDemo.Employee 
@Code 
    ViewData("Title") = "Employee Details" 
End Code 
<h2>Employee Details</h2> 
<table style="font-family:Arial"> 
    <tr> 
     <td> 
      @Model.EmployeeID 
     </td> 
    </tr> 
</table> 

我的問題: 運行代碼我得到以下錯誤:

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

對於行:

Line 11: @Model.EmployeeID

我只是不知道爲什麼沒有對象引用。我在剃刀代碼中獲得模型的智能感知。初始化和賦值給屬性是好的。 Mybe我只是瞎了,誰能幫我解釋爲什麼這不起作用?

回答

1

您需要的模型實例傳遞給視圖:

Function Details() As ActionResult 
    Dim employee As Employee 
    employee = New Employee 
    employee.EmployeeID = 101 
    Return View(employee) 
End Function 
+0

啊,原來如此。非常感謝你現在正在工作!完善! – ruedi