Wednesday, March 2, 2011

[ASP.NET MVC]–Custom DisplayFor partial view for IEnumerable<T>

Notice: This is a post related to ASP.NET MVC version 3. If you are a regular reader of this blog who is only interested in Revit API posts, please change your RSS subscription to the new ‘Revit Only Feed’ – see this post for more information.

In ASP.NET MVC, you can generate a HTML display for a model property by using Html.DisplayFor(model => model.Property); however you may want to create a custom partial view for this display rather than use the default output.

To do this, create a folder called DisplayTemplates under Views/ControllerName and add your partial view in there. To make it automatically choose this template for a certain type of object, you need to name it the name of the Type. For simple types, this is fine, but what about IEnumerable<SomeObject>? Naming your files like this is likely to have problems.

We can get around this with DataAnnotations. In your model, import the System.ComponentModel.DataAnnotations namespace and add [UIHint(“Name”)] attribute to your property, like this:

public IEnumerable<Projects> ProjectsList { get; set; }

Then we can simply create a partial view called ProjectsList in the DisplayTemplates directory


Then in your view you can simply use:

@Html.DisplayFor(model => model.ProjectsList);

And your partial view will be used.

No comments: