尝试使viewmodel项等于变量时出现空值错误

时间:2015-07-31 09:15:31

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

我正在创建一个MVC应用程序,我正在向JIRA发送电子邮件。当我在视图中使用ModelTable时,我最初使用它,但是当我更改它时,ModelType ViewModelClass.ViewModel它也停止了正常工作。

在控制器中:

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将值赋入变量/电子邮件的正确方法,是否有人知道如何正确执行此操作?

1 个答案:

答案 0 :(得分:2)

您需要从控制器方法中删除BindAttribute,或将其更改为<Bind(Include:="iTable")>

您的视图模型不包含名为IssueIDIssueSummaryIssueDescription的属性,只包含名为iTable的属性(后者又包含这些属性)。

但是,您使用视图模型,视图模型应该只包含视图中所需的属性,这意味着您的方法不需要BindAttribute

假设您仅修改了IssueSummary的{​​{1}}和IssueDescription属性(根据您的代码),那么您的视图模型应为

IssueTable