2

Having a little bit of trouble figuring out using a ternary with Razor view engine.

My model has a string property. If that string property is null, I want to render null in the view. If the property is not null, I want it to render the property value with a leading and trailing '.

How can I do this?

UPDATE: Sorry, changed question slightly.

2
  • Can you use the null coalescing opererator? Something like: @Model.MyString ?? "'null'" Commented Oct 11, 2011 at 16:04
  • I'm agree with @Darin Dimitrov. Ternary, loops, C# and stuff makes views ugly. Commented Oct 11, 2011 at 16:21

3 Answers 3

11

You should just be able to use a ternary operator like the title suggests:

@(string.IsNullOrEmpty(Model.Prop) ? "null" : "'" + Model.Prop + "'")
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I was using a '{}' instead of '()'!
6

Assume you have an entity named Test with the First and Last properties:

public class Test {

    public string First { get; set; }

    public string Last { get; set; }
}

You can use DisplayFormat.DataFormatString and DisplayFormat.NullDisplayText to achieve your purpose:

public class Test {

    [Display(Name = "First Name")]
    [DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
    public string First { get; set; }

    [Display(Name = "Last Name")]
    [DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
    public string Last { get; set; }
}

AND in view:

@Html.DisplayFor(model => model.First)

@Html.DisplayFor(model => model.Last)

I change the answer too:

[DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "null")]

Comments

4

Ternary, loops, C# and stuff makes views ugly.

That's what view models are exactly designed to do:

public class MyViewModel
{
    [DisplayFormat(NullDisplayText = "null", DataFormatString = "'{0}'"]
    public string MyProperty { get; set; }
}

and then in your strongly typed view simply:

@model MyViewModel
...
@Html.DisplayFor(x => x.MyProperty)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.