ASP.NET MVC 3 Custom Display Template with UIHint - 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 an HTML line as follows:

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

And a display template with this signature:

 @model MvcApplication1.Models.SomeViewModel 

I get an error: "The model element is of type List<SomeViewModel> , but this dictionary requires a model of type SomeViewModel .".

Which makes sense, but I would hope that the built-in sms MVC templates will start working, look at this IEnumerable something and work out to call my template N times, for example, as is usually done for Html.DisplayFor .

So it looks like [UIHint] redefining this functionality?

Obviously, I can point to another template that accepts the collection and call Html.DisplayForModel() , mostly mimicking MVC emoticons. But I hope to avoid this. Honestly, I'd rather have a foreach loop than having this 1-line wrapper pattern.

Any better ideas?

I like what I want to say: "Hi MVC, output a template for each of these guys. But instead of using the naming convention to find the template, here is a hint."

+8
asp.net-mvc asp.net-mvc-3 razor data-annotations
source share
3 answers

UIHint means "Render this model using template by XXX". Therefore you should declare your displaytemplate "SomeTemplate" with

 @model MvcApplication1.Models.ICollection<SomeViewModel> 

And display each element inside the foreach.

+7
source share

An alternative is to pass the name of the string pattern as follows

 @Html.DisplayFor(model => model.Submodel, "SomeTemplate") 
+3
source share

I ran into the same problem. UIHint seems to be ignored by default for complex types. You can override the behavior, but it is not easy. Thus, a simpler solution would be:

1) Delete the UIHint annotation. 2) Instead, make sure your display template file is named with the type name that you want Html.DisplayFor to iterate over automatically. Therefore, in your case, name the display template file as SomeViewModel.cshtml. That should work. There is no need to explicitly use a for loop. I tried it in MVC4 and it works.

I got the solution at the following link: http://roysvork.wordpress.com/2012/12/09/dynamic-repeating-field-groups-in-asp-net-mvc-with-just-a-dash-of-knockout -js /

+2
source share

All Articles