Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ASP.NET MVC v2 EditorFor and DisplayFor with IEnumerable<T> Generic types

Tags:

asp.net-mvc

I have a IList<Tag> as a property named Tags in my model. How do I name the files for display and editor templates to respect it when I call DisplayFor or EditorFor? Usage:

Model

class MyModel 
{
    IList<Tag> Tags { get; protected set; }
}

View

<%= Html.EditorFor(t => t.Tags) %>

edit I know I can do this, but its not what I want to do.

<%= Html.EditorFor(t => t.Tags, "TagList") %>
like image 561
Daniel A. White Avatar asked Oct 20 '09 13:10

Daniel A. White


3 Answers

Use the attribute [UIHint("Tags")] then create a display template called Tags.ascx in the DisplayTemplates folder.

class MyModel  {     [UIHint("Tags")]     IList<Tag> Tags { get; protected set; } } 

And in the file Tags.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Tag>>" %> <!-- put your Model code here ->  

Works for me

like image 98
Dan Avatar answered Oct 11 '22 04:10

Dan


I had the same problem today. Hope this helps:

forach(var tag in Tags) {
    <%= Html.EditorFor( _ -> tag) %>
}

If you absolutely want to do sth. like

Html.EditorFor(mymodel=>mymodel.Tags)

Then you will have to:

Create a UserControl (TagList.ascx) and add an UIHint attribute to MyModel

class MyModel {
     [UIHint("Taglist")]
     IList<Tag> Tags {get; protected set;}
}
like image 24
Thomasz Avatar answered Oct 11 '22 04:10

Thomasz


I had the same problem as you :-/ but found this useful post which gives you 4 different options to solve the problem :-):

http://blogs.msdn.com/b/stuartleeks/archive/2010/04/01/collections-and-asp-net-mvc-templated-helpers-part-4.aspx

This is also interesting (more or less same solution as one of the solutions in the previous link - but interesting):

http://weblogs.asp.net/rashid/archive/2010/02/09/asp-net-mvc-complex-object-modelmetadata-issue.aspx

like image 39
Lasse Espeholt Avatar answered Oct 11 '22 06:10

Lasse Espeholt