Quantcast
Channel: c# – Full Frontal Nerdity
Viewing all articles
Browse latest Browse all 4

Creating A Simple DisplayFor Template In ASP.NET MVC

$
0
0

When building web applications, the DisplayFor and EditorFor HTML helpers are extremely useful to quickly build pages from your model. However, sometimes you would like a bit more control over their display.

For example, by default, boolean fields show as a disabled dropdown with the value selected. I would prefer to simply output the value – true or false – as plain text.

In order to replace the template used, first create a folder inside of the Shared folder under Views called DisplayTemplates.

Then create a partial view file matching the name of the data type, in this case Boolean.cshtml

Solution explorer with DisplayTemplate

Inside the Boolean.cshtml file, add the following code:

@model Boolean?

@(Model.HasValue? Model.Value.ToString() : "")

That’s all you need to do. Any views that use DisplayFor on a boolean will pick up the new format automatically.

You can do a lot more than what is shown here. This is a pretty good guide to creating simple and advanced EditorFor templates. The same concepts apply for DisplayFor, just a different folder (DisplayTemplates vs EditorTemplates):

Extending Editor Templates for ASP.NET MVC

 


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles



Latest Images