Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create editor templates for Nullable<T> in Razor

been trying to find ways to create editor templates for nullable types using razor. I have properties in a LinqToSQL class that are of types Guid and Nullable. when i use @model Guid?in the first line of the file Guid.cshtml, it always assume Guids as Guid? types. I wanted to create a different editor template for Guid?, but filenames do not accept ? or < or > characters.

please help. thanks.

like image 788
AceMark Avatar asked Dec 29 '10 06:12

AceMark


2 Answers

It seems that for nullable value types the intent is to write one display/editor template that handles both nullable and non-nullable types. Here's an excerpt from a post by Brad Wilson:

When searching for the type name, the simple name is used (i.e., Type.Name) without namespace. Also, if the type is Nullable, we search for T (so you’ll get the Boolean template whether you’re using “bool” or “Nullable”). This means if you’re writing templates for value types, you will need to account for whether the value is nullable or not. You can use the IsNullableValueType property of ModelMetadata to determine if the value is nullable. We’ll see an example of this below with the built-in Boolean template.

So, you would use @model Guid? in your template and check for nulls.

like image 50
Derek Morrison Avatar answered Sep 21 '22 07:09

Derek Morrison


I guess I'll post this as an answer :)

Have you tried @model Nullable<Guid> rather than @model Guid?

like image 3
Buildstarted Avatar answered Sep 22 '22 07:09

Buildstarted