【问题标题】:NullReference Error while assiging values of Modeltype in MVC View (Razor)在 MVC 视图(Razor)中分配模型类型的值时出现空引用错误
【发布时间】:2023-03-25 05:35:01
【问题描述】:

我有以下 MVC

型号:

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.

对于线路:

第 11 行:@Model.EmployeeID

我只是不知道为什么没有对象引用。我在剃刀代码中获得了模型的智能感知。初始化并将值分配给属性是可以的。 Mybe我只是个盲人,谁能帮助我为什么这不起作用?

【问题讨论】:

    标签: vb.net razor model-view-controller model


    【解决方案1】:

    您需要将模型实例传递给视图:

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

    【讨论】:

    • 啊,就是这样。非常感谢它现在正在工作!完美!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多