23

What is Use of UIHint Attribute in MVC . Can anyone please provide me a simple example of how to use it and what it does.

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
user1030181
  • 1,995
  • 5
  • 26
  • 56

2 Answers2

37

When using a Display or Editor template, UIHint will tell it which template to use:

[UIHint("SomeTemplate")]
public class MyViewModel
{
     public string SomeProperty { get; set; }
}

If you create a Display template called SomeTemplate.ascx (since you are MVC2) in the Views/Shared/DisplayTemplates or Views/{Controller}/DisplayTemplates then it will use that template when you do:

@Html.DisplayForModel() // if Model is MyViewModel

or

@Html.DisplayFor(m => m.ModelProperty) // if ModelProperty is of type MyViewModel

edit
If you want to specify this on a property level:

public class MyViewModel
{
    [UIHint("Birthday")]
    public DateTime DateOfBirth { get; set; }
}

You could create a display/editor template called Birthday in the DisplayTemplates or EditorTemplates folder in either /Views/Shared or /Views/{Controller}. Then when you do:

@Html.DisplayFor(m => m.DateOfBirth)

or

@Html.EditorFor(m => m.DateOfBirth)

It will use the template specified in UIHint

Dismissile
  • 32,564
  • 38
  • 174
  • 263
  • Thanks for the Reply Great!! But How t specify on Property level ..need more clear representation please – user1030181 Nov 09 '11 at 19:12
  • 2
    Dang it, that was exactly what I spent an hour looking for how to do. Why do they make it that hard to find this property? – neminem Oct 11 '13 at 22:47
  • 2
    Cannot be used on a `class`, only on properties and fields. – Mrchief Jul 20 '14 at 18:44
  • 1
    Your example `[UIHint("SomeTemplate")]` raises a compiler error "_Attribute 'UIHint' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations._" – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Jun 24 '15 at 08:30
15

UIHint can only be used on a property not on a class declaration as Dismissile states. I am using MVC3 so this may have changed from MVC2.

"Attribute 'UIHint' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations"

Ant
  • 338
  • 2
  • 9