Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from Html.Action to the partial view

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.

like image 440
TheJeff Avatar asked Apr 25 '26 15:04

TheJeff


2 Answers

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

like image 183
DarthVader Avatar answered Apr 28 '26 05:04

DarthVader


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

like image 23
Yusubov Avatar answered Apr 28 '26 07:04

Yusubov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!