dot
dot

Reputation: 15660

populating ViewBag with HTML

I have a controller with a method that is called when a button on my form is clicked. It populates a variable in my viewbag (a string containing html) and then i try to display the contents of this in my view. For some reason, the contents of the viewbag doesnt change.
Here's the code in my controller:

    Function Index() As ActionResult
        Dim TotalPSys As MyBusinessLayer.ListPSysAndMods = New ListPSysAndMods 
        ViewBag.HTMLForMods = "set"
        ViewBag.Test = "123"
        Return View(TotalPLC)
    End Function

  <HttpPost()>
    Function ShowModulesForPSys(ByVal strPSysID As String) As ActionResult
// .... do something....
        returnHTMLString = "<table><tr> <td>Show mods</td><td>Module Name</td></tr>"
        For Each moduleitem In modulelist
            returnHTMLString = returnHTMLString + " <tr> <td width='50%'  style='background-color:#5c87b2'><font color='white'>Number:</font> </td><td>Html.DisplayFor(Function(x) " + moduleitem.SlotNumber + ")</td>"
            returnHTMLString = returnHTMLString + "</tr><tr><td width='50%' style='background-color:#5c87b2'><font color='white'>RevNumber:</font></td>  <td>Html.DisplayFor(Function(x) " + moduleitem.RevisionNumber + ")</td>"
            returnHTMLString = returnHTMLString + "</tr><tr> <td width='50%'  style='background-color:#5c87b2'><font color='white'>IP Address:</font></td><td>Html.DisplayFor(Function(x) " + moduleitem.ModuleIP + ")</td></tr>"

        Next
        returnHTMLString = returnHTMLString + "</table>"
        'ViewData("HTMLForMods") = returnHTMLString
        ViewBag.HTMLForMods = returnHTMLString
        'MsgBox(ViewBag.HTMLForMods)
        ViewBag.Test = "456"
        MsgBox(ViewBag.Test)
        Return RedirectToAction("Index")

    End Function

The code in the view looks like:

         <p>@Html.Raw(ViewBag.HTMLForMods)</p>
         <p>@ViewBag.Test</p>

When the system displays the message box in the controller code, it displays the proper values. But when the view displays, it shows the correct initial values for the viewbag data, and then when i press my submit button, the code in the controller executes properly, but the viewbag displays the old data.

Upvotes: 0

Views: 1403

Answers (1)

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

Looks like you are redirecting to index, so your Viewbag.HtmlForMod will be overwritten by what's defined in the index Action Method.

Upvotes: 1

Related Questions