36

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
KyleMit
  • 35,223
  • 60
  • 418
  • 600
Barış Velioğlu
  • 5,524
  • 14
  • 56
  • 103

5 Answers5

64

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

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
27

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; }
KyleMit
  • 35,223
  • 60
  • 418
  • 600
21

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 ?? "-")
Amadeus Sánchez
  • 2,115
  • 1
  • 22
  • 30
Ghazni
  • 744
  • 6
  • 16
3

Use the null conditional operator:

@UIManager.Member?.Email
Michael Diomin
  • 530
  • 3
  • 13
0
$" ({UIManager.Member.FirstOrDefault()?.EMail})" ?? "N/A"
Jeremy Caney
  • 6,191
  • 35
  • 44
  • 70
Sunitha
  • 1
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 11 '22 at 15:08