Collin O'Connor
Collin O'Connor

Reputation: 1351

Using Html.DisplayFor in mvc with templates

I have a model

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

and a Simple View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<Site.Models.Person>>" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
    <% for (int i = 0 ; i < Model.Count ; i++) {  %>
        <%: Html.DisplayFor(m => m[i])%>
    <% } %>
</body>
</html>

With a Partial View

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Site.Models.Person>" %>
 <h1>A person</h1>
 <div>Name: <%: Html.DisplayFor(x => x.Name)%></div>
 <div>Age: <%: Html.DisplayFor(x => x.Age)%></div>

and single Controller

public ActionResult Index () {
        Person p1 = new Person { Age = 18 , Name = "jon" };
        Person p2 = new Person { Age = 23 , Name = "bob" };

        return View(new List<Person> { p1 , p2 });
    }

The Displayfor in the view should show each person displayed with the Template specified in the partial view, but it is not. Thanks for any help

Upvotes: 1

Views: 5213

Answers (1)

Adeel
Adeel

Reputation: 19238

The partial view name must be Person.ascx placed in shared\DisplayTemplates folder

Upvotes: 6

Related Questions