Asp.Net MVC 5 How to send ViewBag to Partial View
It seems you're expecting this Index
action to be called when you do: @Html.Partial('_LoginPartial')
. That will never happen. Partial
just runs the partial view through Razor with the current view's context and spits out the generated HTML.
If you need additional information for your partial, you can specify a custom ViewDataDictionary
:
@Html.Partial("_LoginPartial", new ViewDataDictionary { Foo = "Bar" });
Which you can then access inside the partial via:
ViewData["Foo"]
You can also use child actions, which is generally preferable if working with a partial view that doesn't need the context of the main view. _LoginPartial
seems like a good candidate, although I'm not sure how exactly you're using it. Ironically, though, the _LoginPartial
view that comes with a default MVC project with individual auth uses child actions.
Basically, the code you have would already work, you would just need to change how you reference it by using Html.Action
instead of Html.Partial
:
@Html.Action("Index")
Notice that you're calling the action here and now the view.
Admin
Updated on December 20, 2020Comments
-
Admin over 3 years
I have a _LoginPartial View and want to send data to it by ViewBag, but the Controller that I'am sending data from, doesn't have a View.
public PartialViewResult Index() { ViewBag.sth = // some data return PartialView("~/Views/Shared/_LoginPartial.cshtml"); }
This code didn't work for me.