asp.net-mvc Html.DisplayTextFor() 有什么意义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3473624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:25:14  来源:igfitidea点击:

What's the point of Html.DisplayTextFor()?

asp.net-mvchtml-helper

提问by Sean Cain

Is there a good reason to use the strongly typed html helper...

是否有充分的理由使用强类型的 html 帮助程序...

<%: Html.DisplayTextFor(model => model.Email) %>

As opposed to...

相对于...

<%: Model.Email %> 

回答by Yngve B-Nilsen

Consider the following Model:

考虑以下模型:

public class MyModel
{
    public string Name { get; set; }

    [DisplayFormat(NullDisplayText = "No value available!")]
    public string Email { get; set; }

}

in my view:

在我看来:

<%= Html.DisplayTextFor(m => m.Email) %>

<%: Model.Email %>

The first line will display "No value available" if we leave the Email to be 'null' whereas the second line will not display anything.

如果我们将电子邮件保留为“空”,则第一行将显示“无可用值”,而第二行将不显示任何内容。

Conclusion: Html.DisplayTextFor will take into consideration the DataAnnotations on your properties, <%: Model.Email %>will not. Also <%: Model.Email %>will throw an "Object reference error" when the value is null, but <%= Html.DisplayTextFor %>wont.

结论: Html.DisplayTextFor 将考虑您的属性上的 DataAnnotations,<%: Model.Email %>不会。也<%: Model.Email %>将抛出一个“对象引用错误”时,该值为空,但<%= Html.DisplayTextFor %>不会。

回答by JcMaltaDev

DisplayTextFor will also get called during "DisplayFor" and "EditFor" execution. This will ensure that any templated helpers will display the text using the correct Templated Helpers if set ... so a change to the single templated helper will propogate through all displays of that text item ... simple display, edit form, create forms etc etc.

DisplayTextFor 也将在“DisplayFor”和“EditFor”执行期间被调用。这将确保任何模板化助手都将使用正确的模板化助手显示文本(如果设置)......因此对单个模板化助手的更改将通过该文本项的所有显示传播......简单的显示,编辑表单,创建表单等等等。

回答by Justin

Well, DisplayTextFor will not break if you do not pass in a model (or pass null). Model.Email will throw an exception on null. So, DisplayTextFor is more robust.

好吧,如果您不传入模型(或传入 null),DisplayTextFor 不会中断。Model.Email 将在 null 上引发异常。因此,DisplayTextFor 更健壮。

The point of the strongly typed helpers is to allow greater compile time checking. This is very handy when refactoring.

强类型助手的重点是允许更多的编译时检查。这在重构时非常方便。

DisplayTextFor allows using a consistent construct (with the other strongly typed helpers) throughout the page. Some people might find that more appealing.

DisplayTextFor 允许在整个页面中使用一致的构造(与其他强类型助手)。有些人可能会觉得这更有吸引力。

DisplayTextFor also allows you to pass the names of templates and fields as parameters.

DisplayTextFor 还允许您将模板和字段的名称作为参数传递。