How can I display a list of objects using DisplayFor, but from a controller in ASP.NET MVC?

Here is scenaio, I have an Employee object and a Company object that has a list of employees.

I have Company.aspx

one that inherits from ViewPage<Company>

.

In Company.aspx I call

Html.DisplayFor(m => m.Employees).

      

I have a partial view Employee.ascx

that inherits from ViewUserControl<Employee

> in my DisplayTemplates folder.

Everything works fine and Company.aspx

provides a partial number Employee.ascx

for each employee.

Now I have two additional methods on my controller GetEmployees

and GetEmployee(Id)

.

In an activity GetEmployee(Id)

I want to return the markup to display this one employee, and in GetEmployees()

I want to display the markup to display all the employees (these two action methods will be called via AJAX).

In the GetEmployee activity, I call

return PartialView("DisplayTemplates\Employee", employee)

      

This works, although I would prefer something like

return PartialViewFor(employee)

      

which will define the name of the view by convention.

Anyway, my question is how to implement the action GetEmployees()

?

I don't want to create more views because, to be honest, I don't understand why I need it.

I have tried the following which fails :)

return Content(New HtmlHelper<IList<Of DebtDto>>(null, null).DisplayFor(m => debts));

      

However, if I can instantiate the HtmlHelper object in my controller, I suppose I can get it to work, but it doesn't feel right.

Any ideas? Am I missing something obvious?

+2


a source to share


1 answer


I've always solved this with a Partial View that iterates over IEnumerable<T>

and calls Html.DisplayFor()

for each item, but then I didn't even know what you can call Html.DisplayFor()

to IEnumerable<T>

and let it automatically render each templated item until you answer this question. Thanks for that, by the way! :)



Anyway, I think your best bet is to simply return PartialView()

, which takes a collection of Employees and displays them one at a time calls Html.DisplayFor()

. It's not quite as elegant as returning an HtmlHelper from your controller, but at least it's simple enough to implement.

+2


a source







All Articles