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.

+3


source to share


4 answers


Try the following:

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 get items

+4


source


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

+1


source


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 :)

0


source


Perhaps Dartwader's suggestion might have worked. This is what I ended up with:

1) Removed controller

2) Called like this:

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

      

3) Here is my code:

@model int[]
@foreach( int item in Model){
...

      

0


source







All Articles