Conditional HTML Attributes using Razor MVC3

后端 未结 3 1721
温柔的废话
温柔的废话 2020-11-27 03:13

The variable strCSSClass often has a value but sometimes is empty.

I do not want to include an empty class=\"\" in this input element\'s HTML, which means if strCSS

3条回答
  •  再見小時候
    2020-11-27 03:45

    I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

    @{
     var htmlAttr = new Dictionary();
     htmlAttr.Add("id", strElementId);
     if (!CSSClass.IsEmpty())
     {
       htmlAttr.Add("class", strCSSClass);
     }
    }
    
    @* ... *@
    
    @Html.TextBox("somename", "", htmlAttr)
    

    If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

提交回复
热议问题