@Html.DisplayFor 语法是什么? [英] What is the @Html.DisplayFor syntax for?

查看:48
本文介绍了@Html.DisplayFor 语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 Razor 中,@Html 做了很多整洁的事情,比如为链接、输入等生成 HTML.

I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc.

但我没有得到 DisplayFor 函数...

But I don't get the DisplayFor function...

我为什么要写:

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

当我可以写作时:

@Model.Title

推荐答案

Html.DisplayFor() 将呈现与属性类型匹配的 DisplayTemplate.

Html.DisplayFor() will render the DisplayTemplate that matches the property's type.

如果找不到,我想它会调用 .ToString().

If it can't find any, I suppose it invokes .ToString().

如果您不了解显示模板,它们是部分视图,可以放在与控制器关联的视图文件夹内的 DisplayTemplates 文件夹中.

If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.

示例:

如果您在视图文件夹的 DisplayTemplates 文件夹(例如 HomeShared) 使用以下代码:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

然后 @Html.DisplayFor(model => model.Title)(假设 Title 是一个字符串)将使用模板并显示 Null string</strong> 如果字符串为 null 或为空.

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

这篇关于@Html.DisplayFor 语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆