0

I am new to MVC (coming from Web Forms). I have a controller with two actions like this:

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 is not passed to the Members view. Why?

chiapa
  • 4,362
  • 11
  • 66
  • 106
w0051977
  • 15,099
  • 32
  • 152
  • 329

2 Answers2

0

ViewBag Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request.

TempData Allows you to store data that will survive for a redirect. Internally it uses the Session as baking store, it's just that after the redirect is made the data is automatically evicted.

So you should use tempData

If Count = 1 Then
    TempData["Message"] = "Member " & id & " was deleted. "
Else
    TempData["Message"] = "There was a problem deleting the record. "

Return RedirectToAction("Members")

OR return a view, instead of redirect...

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")

refrence: ViewBag, ViewData and TempData

Community
  • 1
  • 1
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
-1

Maybe this will work:

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

Since you define the ViewBag variable and then RedirectToAction, the ViewBag value is lost and doesn't make it to the Members View.

chiapa
  • 4,362
  • 11
  • 66
  • 106