ViewBag在_Layout上呈现的部分视图上的动态数据

时间:2017-01-28 20:04:41

标签: asp.net-mvc

这里我在MVC 5中有部分视图

std::apply

...并且控制器将一些动态内容返回给ViewBag

@modelType HOA5.MainMenuModel

<div class="navbar navbar-inverse navbar-fixed-top" id="mainNavbar">
    <div class="container">
        @Html.Raw(ViewBag.htmlstr)
    </div>
</div>

...然后只运行该视图

Function Index() As ActionResult
    Dim vModal As New MainMenuModel
    vModal.MenuHTML = SB.ToString
    Dim MenuHTML As String = ReturnMenu()
    ViewBag.htmlstr = MenuHTML
    Return View("MainMenuView")
End Function

完美运行并插入动态内容。但是,当我将局部视图添加到_Layout

http://localhost:52735/mainMenu/

并运行它

@Html.Partial("~/Views/MainMenu/MainMenuView.vbhtml")

然后出现静态内容,但不是动态内容..还尝试了@RenderAction,@ RenderPartial的变体,但要么是不正确,要么我搞砸了语法!

任何指针都会受到赞赏,因为今天头部被引入太多次了: - )

谢谢

1 个答案:

答案 0 :(得分:-1)

我们常常把事情弄得更复杂: - )

简单的解决方法是使返回HTML字符串的函数成为ActionResult

 Function ReturnMainMenu() As ActionResult
        Try
            strSQL = "SELECT * FROM Customers"
            Using DS As DataSet = ReturnDataSet_Data(strSQL, 2, False)
                For Each row As DataRow In DS.Tables(0).Rows

                Next
            End Using
            Dim vModal As New MainMenuModel
            Dim SB As New StringBuilder
            SB.Append("<div class=""navbar navbar-inverse navbar-fixed-top"" id=""mainNavbar"">")
            SB.Append("<div class=""container"">")
            SB.Append("<div class=""navbar-header"">")
            SB.Append("<button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
            SB.Append("<span class=""icon-bar""></span>")
            SB.Append("<span class=""icon-bar""></span>")
            SB.Append("<span class=""icon-bar""></span>")
            SB.Append("</button>")
            SB.Append("<a class=""navbar-brand"" href=""/"">Add Variable Here xxx</a>") ' Add the variable here
            SB.Append("</div>") ' End of navbar-header

            SB.Append("<div class=""navbar-collapse collapse"">")
            SB.Append("<ul class=""nav navbar-nav"">")
            SB.Append("<li><a href=""/"">Home</a></li></li>")
            SB.Append(" <li><a href=""/eInvoice"">Upload eInvoice</a></li>")
            SB.Append("<li><a href=""/ContactUs"">Contact</a></li>")
            SB.Append("</ul>")
            SB.Append("</div>") 'end of navbar-collapse
            SB.Append("</div>")
            SB.Append("</div>")
            Dim checkstring As String = SB.ToString


            vModal.MenuHTML = SB.ToString

            Return Content(checkstring)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

然后(现在我理解语法)将它添加到_Layout

@Html.Action("ReturnMainMenu", "MainMenu")

......一切正常......