ASP.NET MVC razor: conditional attribute in HTML












66















Code below doesn't seems clean.
Any suggestion to improve the code?



<li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } >
<a @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BusinessDetails", "Business")">Business Details</a>
</li>
<li @if (ViewData["pagename"].ToString() == "Booking policies"){ <text>class="active"</text> }>
<a @if (ViewData["pagename"].ToString() == "Booking policies")
{ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BookingPolicies", "Business")">Booking policies</a>
</li>









share|improve this question























  • Perhaps creating a custom HTML helper that would render out the LI with child link elements?

    – Nick Bork
    Feb 22 '12 at 17:09
















66















Code below doesn't seems clean.
Any suggestion to improve the code?



<li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } >
<a @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BusinessDetails", "Business")">Business Details</a>
</li>
<li @if (ViewData["pagename"].ToString() == "Booking policies"){ <text>class="active"</text> }>
<a @if (ViewData["pagename"].ToString() == "Booking policies")
{ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BookingPolicies", "Business")">Booking policies</a>
</li>









share|improve this question























  • Perhaps creating a custom HTML helper that would render out the LI with child link elements?

    – Nick Bork
    Feb 22 '12 at 17:09














66












66








66


12






Code below doesn't seems clean.
Any suggestion to improve the code?



<li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } >
<a @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BusinessDetails", "Business")">Business Details</a>
</li>
<li @if (ViewData["pagename"].ToString() == "Booking policies"){ <text>class="active"</text> }>
<a @if (ViewData["pagename"].ToString() == "Booking policies")
{ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BookingPolicies", "Business")">Booking policies</a>
</li>









share|improve this question














Code below doesn't seems clean.
Any suggestion to improve the code?



<li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } >
<a @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BusinessDetails", "Business")">Business Details</a>
</li>
<li @if (ViewData["pagename"].ToString() == "Booking policies"){ <text>class="active"</text> }>
<a @if (ViewData["pagename"].ToString() == "Booking policies")
{ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
href="@Url.Action("BookingPolicies", "Business")">Booking policies</a>
</li>






asp.net-mvc asp.net-mvc-3 razor






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 22 '12 at 17:07









MaheshMahesh

76473053




76473053













  • Perhaps creating a custom HTML helper that would render out the LI with child link elements?

    – Nick Bork
    Feb 22 '12 at 17:09



















  • Perhaps creating a custom HTML helper that would render out the LI with child link elements?

    – Nick Bork
    Feb 22 '12 at 17:09

















Perhaps creating a custom HTML helper that would render out the LI with child link elements?

– Nick Bork
Feb 22 '12 at 17:09





Perhaps creating a custom HTML helper that would render out the LI with child link elements?

– Nick Bork
Feb 22 '12 at 17:09












5 Answers
5






active

oldest

votes


















113














MVC has conditional attributes built in...



<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
<div class="@myClass">Content</div>


If @myClass is null, it just won't use the attribute at all...



I know that may not quite solve your current issue, but it is noteworthy!



http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx






share|improve this answer


























  • Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

    – ScottE
    Aug 6 '14 at 19:34








  • 1





    Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

    – GSerg
    Oct 14 '14 at 14:35








  • 1





    Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

    – Alexei Levenkov
    Jan 24 '17 at 20:32



















64














<li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  


You should replace the inline style="..." with a separate classname and use the same syntax there.



However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.






share|improve this answer
























  • Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

    – ctrlplusb
    Mar 15 '13 at 13:22



















18














I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:



public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
{
return MvcHtmlString.Empty;
}

var render = condition != null ? condition() : true;

return render ?
new MvcHtmlString(string.Format("{0}="{1}"", name, HttpUtility.HtmlAttributeEncode(value))) :
MvcHtmlString.Empty;
}


Once defined, I can use this method in my Razor views:



<li @(Html.Attr("class", "new", () => example.isNew))>
...
</li>


The above code will render <li class="new">...</li> if example.isNew == true, if not will omit the entire class attribute.






share|improve this answer



















  • 1





    Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

    – T-moty
    Dec 8 '16 at 18:16











  • Good job mate..

    – Greg R Taylor
    Feb 17 '17 at 5:44











  • I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

    – Ben Sewards
    Apr 10 '17 at 15:30



















2














In MVC4



<!DOCTYPE html>
<html>
<head>
</head>
<body>
@{
string css = "myDiv";
}
<div class='@css'></div>
</body>
</html>


or



<!DOCTYPE html>
<html>
<head>
</head>
<body>
@{
string css = "class=myDiv";
}
<div @css></div>
</body>
</html>


More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/






share|improve this answer































    0














    Approach with TagWrap extension method. Code for your question would look like this:



    @using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
    {
    var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
    if(condition)
    {
    anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
    }
    using (Html.TagWrap("a", anchorAttrs))
    {
    <text>Business Details</text>
    }
    }


    TagWrap extension methods




    using Microsoft.AspNetCore.Mvc.ViewFeatures;




    public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
    {
    return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
    }

    public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
    {
    var tag = new TagBuilder(tagName);
    tag.MergeAttributes(data);

    htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

    return new DisposableAction(() =>
    htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
    }


    Helper class used for rendering closing tag on Dispose



    public class DisposableAction : IDisposable
    {
    private readonly Action DisposeAction;

    public DisposableAction(Action action)
    {
    DisposeAction = action;
    }

    public void Dispose()
    {
    DisposeAction();
    }
    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9399531%2fasp-net-mvc-razor-conditional-attribute-in-html%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      113














      MVC has conditional attributes built in...



      <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
      <div class="@myClass">Content</div>


      If @myClass is null, it just won't use the attribute at all...



      I know that may not quite solve your current issue, but it is noteworthy!



      http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx






      share|improve this answer


























      • Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

        – ScottE
        Aug 6 '14 at 19:34








      • 1





        Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

        – GSerg
        Oct 14 '14 at 14:35








      • 1





        Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

        – Alexei Levenkov
        Jan 24 '17 at 20:32
















      113














      MVC has conditional attributes built in...



      <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
      <div class="@myClass">Content</div>


      If @myClass is null, it just won't use the attribute at all...



      I know that may not quite solve your current issue, but it is noteworthy!



      http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx






      share|improve this answer


























      • Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

        – ScottE
        Aug 6 '14 at 19:34








      • 1





        Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

        – GSerg
        Oct 14 '14 at 14:35








      • 1





        Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

        – Alexei Levenkov
        Jan 24 '17 at 20:32














      113












      113








      113







      MVC has conditional attributes built in...



      <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
      <div class="@myClass">Content</div>


      If @myClass is null, it just won't use the attribute at all...



      I know that may not quite solve your current issue, but it is noteworthy!



      http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx






      share|improve this answer















      MVC has conditional attributes built in...



      <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
      <div class="@myClass">Content</div>


      If @myClass is null, it just won't use the attribute at all...



      I know that may not quite solve your current issue, but it is noteworthy!



      http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 10 '18 at 6:36









      Anirudha Gupta

      5,97253760




      5,97253760










      answered Feb 22 '12 at 17:20









      jcreamer898jcreamer898

      6,45843454




      6,45843454













      • Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

        – ScottE
        Aug 6 '14 at 19:34








      • 1





        Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

        – GSerg
        Oct 14 '14 at 14:35








      • 1





        Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

        – Alexei Levenkov
        Jan 24 '17 at 20:32



















      • Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

        – ScottE
        Aug 6 '14 at 19:34








      • 1





        Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

        – GSerg
        Oct 14 '14 at 14:35








      • 1





        Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

        – Alexei Levenkov
        Jan 24 '17 at 20:32

















      Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

      – ScottE
      Aug 6 '14 at 19:34







      Be careful that your class name isn't 'active' or you'll have an entry class attribute. No idea why.

      – ScottE
      Aug 6 '14 at 19:34






      1




      1





      Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

      – GSerg
      Oct 14 '14 at 14:35







      Is there a way to achieve same null-respecting behaviour when calling to html helpers passing the anonymous htmlProperties object? E.g. I want to conditionally pass attribute disabled, like @Html.TextBoxFor(lambda, new { disabled = condition ? true : null }), but that still renders disabled="" when disabled was null, which is the same as rendring disabled="anything" because disabled is active when the attribute is present, regardless of the value. Found stackoverflow.com/q/7978137/11683 on the topic, but are there better ways nowadays I wonder?

      – GSerg
      Oct 14 '14 at 14:35






      1




      1





      Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

      – Alexei Levenkov
      Jan 24 '17 at 20:32





      Side note: "data-..." attributes can't be conditional and render empty value even for null (stackoverflow.com/questions/13267619/…)

      – Alexei Levenkov
      Jan 24 '17 at 20:32













      64














      <li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  


      You should replace the inline style="..." with a separate classname and use the same syntax there.



      However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.






      share|improve this answer
























      • Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

        – ctrlplusb
        Mar 15 '13 at 13:22
















      64














      <li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  


      You should replace the inline style="..." with a separate classname and use the same syntax there.



      However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.






      share|improve this answer
























      • Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

        – ctrlplusb
        Mar 15 '13 at 13:22














      64












      64








      64







      <li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  


      You should replace the inline style="..." with a separate classname and use the same syntax there.



      However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.






      share|improve this answer













      <li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  


      You should replace the inline style="..." with a separate classname and use the same syntax there.



      However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Feb 22 '12 at 17:10









      SLaksSLaks

      688k13916451768




      688k13916451768













      • Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

        – ctrlplusb
        Mar 15 '13 at 13:22



















      • Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

        – ctrlplusb
        Mar 15 '13 at 13:22

















      Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

      – ctrlplusb
      Mar 15 '13 at 13:22





      Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).

      – ctrlplusb
      Mar 15 '13 at 13:22











      18














      I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:



      public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
      {
      if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
      {
      return MvcHtmlString.Empty;
      }

      var render = condition != null ? condition() : true;

      return render ?
      new MvcHtmlString(string.Format("{0}="{1}"", name, HttpUtility.HtmlAttributeEncode(value))) :
      MvcHtmlString.Empty;
      }


      Once defined, I can use this method in my Razor views:



      <li @(Html.Attr("class", "new", () => example.isNew))>
      ...
      </li>


      The above code will render <li class="new">...</li> if example.isNew == true, if not will omit the entire class attribute.






      share|improve this answer



















      • 1





        Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

        – T-moty
        Dec 8 '16 at 18:16











      • Good job mate..

        – Greg R Taylor
        Feb 17 '17 at 5:44











      • I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

        – Ben Sewards
        Apr 10 '17 at 15:30
















      18














      I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:



      public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
      {
      if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
      {
      return MvcHtmlString.Empty;
      }

      var render = condition != null ? condition() : true;

      return render ?
      new MvcHtmlString(string.Format("{0}="{1}"", name, HttpUtility.HtmlAttributeEncode(value))) :
      MvcHtmlString.Empty;
      }


      Once defined, I can use this method in my Razor views:



      <li @(Html.Attr("class", "new", () => example.isNew))>
      ...
      </li>


      The above code will render <li class="new">...</li> if example.isNew == true, if not will omit the entire class attribute.






      share|improve this answer



















      • 1





        Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

        – T-moty
        Dec 8 '16 at 18:16











      • Good job mate..

        – Greg R Taylor
        Feb 17 '17 at 5:44











      • I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

        – Ben Sewards
        Apr 10 '17 at 15:30














      18












      18








      18







      I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:



      public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
      {
      if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
      {
      return MvcHtmlString.Empty;
      }

      var render = condition != null ? condition() : true;

      return render ?
      new MvcHtmlString(string.Format("{0}="{1}"", name, HttpUtility.HtmlAttributeEncode(value))) :
      MvcHtmlString.Empty;
      }


      Once defined, I can use this method in my Razor views:



      <li @(Html.Attr("class", "new", () => example.isNew))>
      ...
      </li>


      The above code will render <li class="new">...</li> if example.isNew == true, if not will omit the entire class attribute.






      share|improve this answer













      I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:



      public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
      {
      if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
      {
      return MvcHtmlString.Empty;
      }

      var render = condition != null ? condition() : true;

      return render ?
      new MvcHtmlString(string.Format("{0}="{1}"", name, HttpUtility.HtmlAttributeEncode(value))) :
      MvcHtmlString.Empty;
      }


      Once defined, I can use this method in my Razor views:



      <li @(Html.Attr("class", "new", () => example.isNew))>
      ...
      </li>


      The above code will render <li class="new">...</li> if example.isNew == true, if not will omit the entire class attribute.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Apr 9 '14 at 20:30









      defrostdefrost

      33626




      33626








      • 1





        Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

        – T-moty
        Dec 8 '16 at 18:16











      • Good job mate..

        – Greg R Taylor
        Feb 17 '17 at 5:44











      • I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

        – Ben Sewards
        Apr 10 '17 at 15:30














      • 1





        Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

        – T-moty
        Dec 8 '16 at 18:16











      • Good job mate..

        – Greg R Taylor
        Feb 17 '17 at 5:44











      • I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

        – Ben Sewards
        Apr 10 '17 at 15:30








      1




      1





      Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

      – T-moty
      Dec 8 '16 at 18:16





      Very elegant way for do that. But instead of Func<bool> lambda, i will prefer a simple bool? parameter, because it's simpler: <li @Html.Attr("class", "new", example.isNew)>

      – T-moty
      Dec 8 '16 at 18:16













      Good job mate..

      – Greg R Taylor
      Feb 17 '17 at 5:44





      Good job mate..

      – Greg R Taylor
      Feb 17 '17 at 5:44













      I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

      – Ben Sewards
      Apr 10 '17 at 15:30





      I like this approach because a lot of the custom JavaScript in my app will still run when the attribute name is still there. And at least this doesn't make you repeat the same div because of attribute differences. Thanks!

      – Ben Sewards
      Apr 10 '17 at 15:30











      2














      In MVC4



      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      @{
      string css = "myDiv";
      }
      <div class='@css'></div>
      </body>
      </html>


      or



      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      @{
      string css = "class=myDiv";
      }
      <div @css></div>
      </body>
      </html>


      More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/






      share|improve this answer




























        2














        In MVC4



        <!DOCTYPE html>
        <html>
        <head>
        </head>
        <body>
        @{
        string css = "myDiv";
        }
        <div class='@css'></div>
        </body>
        </html>


        or



        <!DOCTYPE html>
        <html>
        <head>
        </head>
        <body>
        @{
        string css = "class=myDiv";
        }
        <div @css></div>
        </body>
        </html>


        More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/






        share|improve this answer


























          2












          2








          2







          In MVC4



          <!DOCTYPE html>
          <html>
          <head>
          </head>
          <body>
          @{
          string css = "myDiv";
          }
          <div class='@css'></div>
          </body>
          </html>


          or



          <!DOCTYPE html>
          <html>
          <head>
          </head>
          <body>
          @{
          string css = "class=myDiv";
          }
          <div @css></div>
          </body>
          </html>


          More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/






          share|improve this answer













          In MVC4



          <!DOCTYPE html>
          <html>
          <head>
          </head>
          <body>
          @{
          string css = "myDiv";
          }
          <div class='@css'></div>
          </body>
          </html>


          or



          <!DOCTYPE html>
          <html>
          <head>
          </head>
          <body>
          @{
          string css = "class=myDiv";
          }
          <div @css></div>
          </body>
          </html>


          More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 30 '13 at 11:27









          David SlavíkDavid Slavík

          7321021




          7321021























              0














              Approach with TagWrap extension method. Code for your question would look like this:



              @using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
              {
              var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
              if(condition)
              {
              anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
              }
              using (Html.TagWrap("a", anchorAttrs))
              {
              <text>Business Details</text>
              }
              }


              TagWrap extension methods




              using Microsoft.AspNetCore.Mvc.ViewFeatures;




              public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
              {
              return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
              }

              public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
              {
              var tag = new TagBuilder(tagName);
              tag.MergeAttributes(data);

              htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

              return new DisposableAction(() =>
              htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
              }


              Helper class used for rendering closing tag on Dispose



              public class DisposableAction : IDisposable
              {
              private readonly Action DisposeAction;

              public DisposableAction(Action action)
              {
              DisposeAction = action;
              }

              public void Dispose()
              {
              DisposeAction();
              }
              }





              share|improve this answer




























                0














                Approach with TagWrap extension method. Code for your question would look like this:



                @using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
                {
                var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
                if(condition)
                {
                anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
                }
                using (Html.TagWrap("a", anchorAttrs))
                {
                <text>Business Details</text>
                }
                }


                TagWrap extension methods




                using Microsoft.AspNetCore.Mvc.ViewFeatures;




                public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
                {
                return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
                }

                public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
                {
                var tag = new TagBuilder(tagName);
                tag.MergeAttributes(data);

                htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

                return new DisposableAction(() =>
                htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
                }


                Helper class used for rendering closing tag on Dispose



                public class DisposableAction : IDisposable
                {
                private readonly Action DisposeAction;

                public DisposableAction(Action action)
                {
                DisposeAction = action;
                }

                public void Dispose()
                {
                DisposeAction();
                }
                }





                share|improve this answer


























                  0












                  0








                  0







                  Approach with TagWrap extension method. Code for your question would look like this:



                  @using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
                  {
                  var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
                  if(condition)
                  {
                  anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
                  }
                  using (Html.TagWrap("a", anchorAttrs))
                  {
                  <text>Business Details</text>
                  }
                  }


                  TagWrap extension methods




                  using Microsoft.AspNetCore.Mvc.ViewFeatures;




                  public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
                  {
                  return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
                  }

                  public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
                  {
                  var tag = new TagBuilder(tagName);
                  tag.MergeAttributes(data);

                  htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

                  return new DisposableAction(() =>
                  htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
                  }


                  Helper class used for rendering closing tag on Dispose



                  public class DisposableAction : IDisposable
                  {
                  private readonly Action DisposeAction;

                  public DisposableAction(Action action)
                  {
                  DisposeAction = action;
                  }

                  public void Dispose()
                  {
                  DisposeAction();
                  }
                  }





                  share|improve this answer













                  Approach with TagWrap extension method. Code for your question would look like this:



                  @using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
                  {
                  var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
                  if(condition)
                  {
                  anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
                  }
                  using (Html.TagWrap("a", anchorAttrs))
                  {
                  <text>Business Details</text>
                  }
                  }


                  TagWrap extension methods




                  using Microsoft.AspNetCore.Mvc.ViewFeatures;




                  public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
                  {
                  return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
                  }

                  public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
                  {
                  var tag = new TagBuilder(tagName);
                  tag.MergeAttributes(data);

                  htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

                  return new DisposableAction(() =>
                  htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
                  }


                  Helper class used for rendering closing tag on Dispose



                  public class DisposableAction : IDisposable
                  {
                  private readonly Action DisposeAction;

                  public DisposableAction(Action action)
                  {
                  DisposeAction = action;
                  }

                  public void Dispose()
                  {
                  DisposeAction();
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 10 '18 at 6:31









                  Pavlo NeymanPavlo Neyman

                  5,61932125




                  5,61932125






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9399531%2fasp-net-mvc-razor-conditional-attribute-in-html%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas