If value is null put an empty string on razor temp

2020-05-24 19:59发布

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

5条回答
倾城 Initia
2楼-- · 2020-05-24 20:42

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; }
查看更多
Rolldiameter
3楼-- · 2020-05-24 20:42

you don't need attribute when it's value's null

    @(UIManager.Member == null ? "" : "value=" + UIManager.Member.EMail)
查看更多
贪生不怕死
4楼-- · 2020-05-24 20:45

Use the null conditional operator:

@UIManager.Member?.Email
查看更多
The star\"
5楼-- · 2020-05-24 20:56

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).

查看更多
劳资没心,怎么记你
6楼-- · 2020-05-24 21:02

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 ?? "-")
查看更多
登录 后发表回答