Question

I'm still relatively new to MVC 3. I need to pass data from my @Html.Action methods through the controller to a partial view.

So here is my flow.

I'll call @Html.Action like this:

@Html.Action("SidebarMain", "Home", new List<int>(new int[] {1, 2, 3}))

Then it will hit 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 the data like so:

@model List<int>

@{
    ViewBag.Title = "SidebarMain";
    Layout = null;
}

<div>
@foreach (int item in Model)
{
    <div>@item</div>
}
</div>

BUT: I'm getting a null exception for the Model, meaning It's not passing through.

Was it helpful?

Solution

Try this:

Html.Action("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })

And put a breakpoint in your SidebarMain Action to see, if you are getting items

OTHER TIPS

In short: your code is missing the items parameter name in the Html.Action(). Other than that the code should be functional.

Html.Action("SidebarMain", "Home", new {items = new List<int>(new int[] {1, 2, 3}) })

As a suggested practice, i would use a dedicated ViewModel in my view rather than just sending the array of integers. Because, in this way of a clean ViewModel - a container of your properties that you display in the view, your code may add other properties later on, as our code always evolves.

Reference to the usage of a ViewModel concept: Exercise 5: Creating a View Model

Good answer from DarthVader. Are you returning this as Ajax? If you are embedding it in a main view, you should really return it as a PartialView with

return PartialView("SidebarMain", model);

This is where SidebarMain is the name of the partial view that you are returning. Try this in combination with what DarthVader suggested and make sure that you're getting a model to pass back to the view.

After posting, I realized that you are using Html.Action. If this is a true sidebar, it SHOULD be loaded with ajax as a partial view and you should be calling

Ajax.ActionLink("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })

This will allow you stay on your current page. If you aren't looking for ajax functionality, I apologize for the rabbit trail :)

DarthVader's suggestion may have worked. This is what I ended up doing:

1) Removed the controller

2) Called it like this:

@{Html.RenderPartial("SidebarMain", new int[] {1,3,4,2});}

3) Here is my view code:

@model int[]
@foreach( int item in Model){
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top