How to add a second css class with a conditional value in razor MVC 4

后端 未结 4 841
傲寒
傲寒 2021-01-30 02:32

While Microsoft has created some automagic rendering of html attributes in razor MVC4, it took me quite some time to find out how to render a second css class on an element, bas

相关标签:
4条回答
  • 2021-01-30 03:10

    I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:

    Your answer (assuming this works, I haven't tried this):

    <div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
    

    Second option:

    @if (Model.Details.Count > 0) {
        <div class="details show">
    }
    else {
        <div class="details hide">
    }
    

    Third option:

    <div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
    
    0 讨论(0)
  • 2021-01-30 03:26

    You can add property to your model as follows:

        public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
    

    and then your view will be simpler and will contain no logic at all:

        <div class="details @Model.DetailsClass"/>
    

    This will work even with many classes and will not render class if it is null:

        <div class="@Model.Class1 @Model.Class2"/>
    

    with 2 not null properties will render:

        <div class="class1 class2"/>
    

    if class1 is null

        <div class=" class2"/>
    
    0 讨论(0)
  • 2021-01-30 03:33

    This:

        <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">
    

    will render this:

        <div class="details hide">
    

    and is the mark-up I want.

    0 讨论(0)
  • 2021-01-30 03:35

    You can use String.Format function to add second class based on condition:

    <div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">
    
    0 讨论(0)
提交回复
热议问题