Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Custom Display Template With UIHint - For Loop Required?

If i have a ViewModel like this:

public class MyViewModel
{
   [UIHint("SomeTemplate")]
   public ICollection<SomeViewModel> Submodel { get; set; }
}

And a strongly-typed View with a line of HTML like this:

@Html.DisplayFor(model => model.Submodel)

And a display template with a signature like this:

@model MvcApplication1.Models.SomeViewModel

I get an error saying "the model item is of type List<SomeViewModel> but this dictionary requires a model of type SomeViewModel.".

Which makes sense, but i would have hoped the built-in templating smarts of MVC would kick in, see it's a IEnumerable of something and work out to call my template N amount of times, like how it usually does for Html.DisplayFor without the hint.

So it looks like [UIHint] overrides that functionality?

Obviously i can point to another template which accepts the collection, and calls Html.DisplayForModel(), basically emulating MVC smarts. But i am hoping to avoid that. Honestly i would rather do a foreach loop than having that 1 line "wrapper" template.

Any better ideas?

It's like i want to say: "Hey MVC, render out a template for each one of these guys. But instead of using name-convention to find the template, here's a hint".

like image 863
RPM1984 Avatar asked May 23 '11 06:05

RPM1984


1 Answers

UIHint means "Render this model using the template named XXX". So you have to declare your displaytemplate "SomeTemplate" with

@model MvcApplication1.Models.ICollection<SomeViewModel>

And display each item inside a foreach.

like image 192
mathieu Avatar answered Oct 16 '22 05:10

mathieu