If value is null put an empty string on razor template?

喜你入骨 提交于 2020-01-12 02:30:15

问题


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.EMail has a value, put its value. How can I do that?

Normal Input:

<input name="EMail" id="SignUpEMail" type="text" class="Input" 
       value="@UIManager.Member.EMail" validate="RequiredField" />

Razor Syntax Attempt:

<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

回答1:


If sounds like you just want:

@(UIManager.Member == null ? "" : UIManager.Member.Email)

Note the locations of the brackets is critical; with razor, @(....) defines an explicit range to the code - hence anything outside the brackets is treated as markup (not code).




回答2:


This is exactly what the NullDisplayText property on [DisplayFormat] attribute is for.

Add this directly on your model:

[DisplayFormat(NullDisplayText="", ApplyFormatInEditMode=true)]
public string EMail { get; set; }



回答3:


To Check some property of a model in cshtml.

@if(!string.IsNullOrEmpty(Model.CUSTOM_PROPERTY))
{
    <p>@Model.CUSTOM_PROPERTY</p>
}
else
{
    <p> - </p>
}

so best way to do this:

@(Model.CUSTOM_PROPERTY ?? "-")



回答4:


Use the null conditional operator:

@UIManager.Member?.Email


来源:https://stackoverflow.com/questions/7089725/if-value-is-null-put-an-empty-string-on-razor-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!