Search code examples
asp.net-mvcasp.net-mvc-4viewbag

ViewBag not seen by view when view specified explicitly


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?


Solution

  • 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