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
  • 30,350
  • 66
  • 462
  • 664
Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

5 Answers5

67

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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
  • 30,350
  • 66
  • 462
  • 664
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 Sanchez
  • 2,375
  • 2
  • 25
  • 31
Ghazni
  • 826
  • 8
  • 16
3

Use the null conditional operator:

@UIManager.Member?.Email
Michael Diomin
  • 530
  • 3
  • 13
0
$" ({UIManager.Member.FirstOrDefault()?.EMail})" ?? "N/A"
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
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