Passing data from Html.Action to partial view
I'm still relatively new to MVC 3. I need to pass data from my @ Html.Action methods through a controller to a partial view.
So here's my flow.
I will call @ Html.Action like this:
@Html.Action("SidebarMain", "Home", new List<int>(new int[] {1, 2, 3}))
Then it will go to my controller. Here is my method in my home controller:
public ActionResult SidebarMain(List<int> items)
{
return View(items);
}
Then my Partial View should be able to access data like this:
@model List<int>
@{
ViewBag.Title = "SidebarMain";
Layout = null;
}
<div>
@foreach (int item in Model)
{
<div>@item</div>
}
</div>
BUT: I am getting a null exception for the model, meaning it does not get through.
source to share
In short: your code is missing the parameter name items in Html.Action()
. In addition, the code must be functional.
Html.Action("SidebarMain", "Home", new {items = new List<int>(new int[] {1, 2, 3}) })
As a recommended practice, I would use the highlighted one ViewModel
in my view instead of just sending an array of integers. Since this is a clean ViewModel
container of your properties displayed in the view, your code can add other properties later on as our code is always evolving.
ViewModel Concept Reference: Exercise 5: Creating a ViewModel
source to share
Good answer from Dartwader. Are you returning this as Ajax? If you embed it in the main view you should really return it as a PartialView with
return PartialView("SidebarMain", model);
Here SidebarMain is the name of the partial view you are returning. Try this in conjunction with what DarthVader suggested and make sure you get the model to come back to watch.
After posting, I realized that you are using Html.Action. If it is a true sidebar it MUST be loaded with ajax as a partial view and you should call
Ajax.ActionLink("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })
This will keep you on the current page. If you are not looking for ajax functionality, I apologize for the rabbit trail :)
source to share