LeonidasFett
LeonidasFett

Reputation: 3132

Passing model from view to controller using Html.RenderAction results in model being null

I have following model:

public class Foo
{
    public List<Employee> Employees{ get; set; }
    public List<Company> Companies{ get; set; }
    public List<Admin> Admins{ get; set; }
}

Then I have my controller actions:

public ActionResult Index()
{
    Foo model = GetFooFromSomewhere();
    return PartialView("Index", model);
} 

public ActionResult Employees(List<Employee> model)
{
    return PartialView("Employees", model);
}

public ActionResult Companies(List<Company> model)
{
    return PartialView("Companies", model);
}

public ActionResult Admins(List<Admin> model)
{
    return PartialView("Admins", model);
}

Then I have my views

Index.cshml:

@model Foo
@if(Model.Employees.Count > 0)
{
    @{Html.RenderAction("Employees", "Config", Model.Employees);}
}
@if(Model.Companies.Count > 0)
{
    @{Html.RenderAction("Companies", "Config", Model.Companies);}
}
@if(Model.Admins.Count > 0)
{
    @{Html.RenderAction("Admins", "Config", Model.Admins);}
}

Employees.cshtml:

@model List<Employee>

//Display model here

Companies.cshtml

@model List<Company>

//Display model here

Admins.cshtml

@model List<Admin>

//Display model here

As you can see, I use Index.cshtml to get a object that contains multiple lists. This is because I need to hide the actions if no items are found in the list/s. However, when I pass them to the controller again using @Html.RenderAction(...), I get null inside the controller action when I am expecting a List. Why?

Upvotes: 1

Views: 1703

Answers (2)

Lucarob
Lucarob

Reputation: 66

Try in this way: Controller:

public ActionResult Admins(List<Admin> m)
{
    return PartialView("Admins", m);
}

View:

@{Html.RenderAction("Admins", "Config", new { m = Model.Admins });}

Upvotes: 3

anmarti
anmarti

Reputation: 5143

You have to pass the model initialized to the Index view in the controller.

public ActionResult Index()
{
   Foo model = GetFooFromSomewhere();
   return PartialView("Index", model);
} 

Upvotes: 1

Related Questions