我是MVC的新手(来自Web Forms)。我有一个控制器,有两个这样的动作:
Public Function Delete(ByVal id As Nullable(Of Integer)) As ActionResult
Dim Count As Integer = IModel.DeleteMember(id)
If Count = 1 Then
ViewBag.Message = "Member " & id & " was deleted. "
Else
ViewBag.Message = "There was a problem deleting the record. "
End If
Return RedirectToAction("Members")
End Function
ViewBag未传递给Members视图。为什么呢?
答案 0 :(得分:0)
ViewBag
允许您将数据存储在将在相应视图中使用的控制器操作中。这假定操作返回视图并且不重定向。仅在当前请求期间生活。
TempData
允许您存储为重定向而存活的数据。在内部,它使用Session作为烘焙商店,只是在重定向之后,数据被自动驱逐。
所以你应该使用tempData
If Count = 1 Then
TempData["Message"] = "Member " & id & " was deleted. "
Else
TempData["Message"] = "There was a problem deleting the record. "
Return RedirectToAction("Members")
或者返回一个视图,而不是重定向......
Dim Count As Integer = IModel.DeleteMember(id)
If Count = 1 Then
ViewBag.Message = "Member " & id & " was deleted. "
Else
ViewBag.Message = "There was a problem deleting the record. "
End If
Return View("Members")
答案 1 :(得分:-1)
也许这会奏效:
Public static String msg
...
Public Function Delete(ByVal id As Nullable(Of Integer)) As ActionResult
Dim Count As Integer = IModel.DeleteMember(id)
If Count = 1 Then
msg = "Member " & id & " was deleted. "
Else
msg = "There was a problem deleting the record. "
End If
Return RedirectToAction("Members")
End Function
Public Function Members() As ActionResult
ViewBag.Message = msg;
Return View()
End Function
由于您定义了ViewBag
变量,然后定义了RedirectToAction
,ViewBag
值将丢失,并且不会显示给会员视图。