asp.net-mvc 如果值为 null 在剃刀模板上放一个空字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7089725/
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
If value is null put an empty string on razor template?
提问by Bar?? Velio?lu
I have a razor template like below. I want to check if the value in the input field is null, put a empty string, if the @UIManager.Member.EMailhas a value, put its value. How can I do that?
我有一个如下所示的剃刀模板。我想检查输入字段中的值是否为空,放一个空字符串,如果@UIManager.Member.EMail有值,放它的值。我怎样才能做到这一点?
Normal Input:
正常输入:
<input name="EMail" id="SignUpEMail" type="text" class="Input"
value="@UIManager.Member.EMail" validate="RequiredField" />
Razor Syntax Attempt:
Razor 语法尝试:
<input name="EMail" id="SignUpEMail" type="text" class="Input" validate="RequiredField"
value="@(UIManager.Member == null) ? string.Empty : UIManager.Member.EMail" />
The value is shown in the input field is:
输入字段中显示的值是:
True ? string.Empty : UIBusinessManager.MemberCandidate.EMail
回答by Marc Gravell
If sounds like you just want:
如果听起来你只是想要:
@(UIManager.Member == null ? "" : UIManager.Member.Email)
Note the locations of the brackets is critical; with razor, @(....)defines an explicitrange to the code - hence anything outsidethe brackets is treated as markup (not code).
注意括号的位置很关键;使用 razor,@(....)定义代码的显式范围 - 因此括号外的任何内容都被视为标记(不是代码)。
回答by KyleMit
This is exactly what the NullDisplayTextproperty on [DisplayFormat]attributeis for.
这正是NullDisplayText属性上的[DisplayFormat]属性的用途。
Add this directly on your model:
将其直接添加到您的模型上:
[DisplayFormat(NullDisplayText="", ApplyFormatInEditMode=true)]
public string EMail { get; set; }
回答by Ghazni
To Check some property of a model in cshtml.
在 cshtml 中检查模型的某些属性。
@if(!string.IsNullOrEmpty(Model.CUSTOM_PROPERTY))
{
<p>@Model.CUSTOM_PROPERTY</p>
}
else
{
<p> - </p>
}
so best way to do this:
所以最好的方法是:
@(Model.CUSTOM_PROPERTY ?? "-")
回答by Michael Diomin
回答by mohamad dianati
you don't need attribute when it's value's null
当它的值为 null 时,你不需要属性
@(UIManager.Member == null ? "" : "value=" + UIManager.Member.EMail)

