试图使视图模型项等于变量时出现空值错误
本文关键字:变量 错误 空值 视图 模型 于变量 | 更新日期: 2023-09-27 18:05:46
我正在创建一个MVC应用程序,我正在向JIRA发送电子邮件。我最初有它的工作,当我有ModelType在视图只是IssueTable,但当我改变它也ModelType ViewModelClass。
在控制器中:
Public Function SubmitIssue(issuetable As IssueTable, test As IssueTracker.ClientUserProjectIssue ) As ActionResult
Dim mail As New MailMessage()
mail.Subject = issuetable.IssueSummary
Dim body As String = test.iTable.IssueDescription
mail.Body = body
smtp.Send(mail)
在视图中:
@ModelType IssueTable
@Html.EditorFor(Function(model) model.IssueSummary)
@Html.EditorFor(Function(model) model.IssueDescription)
这最初工作,但我需要有多个表来发送数据,所以我创建了一个viewModel这样:
Public Class ViewModel
Public proTableList As List(Of ProjectType)
Public cTableList As List(Of ClientTable)
Public proTable As ProjectType
Public iTable As IssueTableViewModel
End Class
Public Class IssueTableViewModel
Public IssueSummary As String
Public IssueDescription As String
End Class
在视图中,我显示的信息如下:
@ModelType IssueTracker.ViewModel
@Html.EditorFor(Function(model) model.iTable.IssueSummary)
@Html.EditorFor(Function(model) model.iTable.IssueDescription)
现在问题在于我的控制器因为我试图像这样填充描述和摘要的方式我得到了一个空错误:
Public Function SubmitIssue(issuetable As IssueTable, test As IssueTracker.ClientUserProjectIssue ) As ActionResult
Dim mail As New MailMessage()
mail.Subject = test.iTable.IssueSummary
Dim body As String = test.iTable.IssueDescription
mail.Body = body
smtp.Send(mail)
正如你所看到的,除了明显的ViewModel类添加到代码中,它是完全相同的。
这显然不能通过使用viewModel获得值到变量/电子邮件的正确方式,有人知道我如何才能正确做到这一点吗?
您需要从控制器方法中删除BindAttribute
,或者将其更改为<Bind(Include:="iTable")>
你的视图模型不包含名为IssueID
, IssueSummary
和IssueDescription
的属性,只有一个名为iTable
的属性(它反过来包含这些属性)。
然而,你使用一个视图模型,一个视图模型应该只包含你在视图中需要的属性,这意味着你不应该在你的方法上需要一个BindAttribute
。
假设您只编辑IssueTable
的IssueSummary
和IssueDescription
属性(根据您的代码),那么您的视图模型应该是
Public Class ViewModel
Public proTableList As List(Of ProjectType)
Public cTableList As List(Of ClientTable)
Public proTable As ProjectType
// Public iTable As IssueTable // delete this
Public IssueSummary As String // add this
Public IssueDescription As String // add this
End Class