ASP.NET MVC Razor: Ternary

2019-01-20 15:29发布

问题:

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.

回答1:

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

@(string.IsNullOrEmpty(Model.Prop) ? "null" : "'" + Model.Prop + "'")


回答2:

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")]


回答3:

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)