ASP.NET MVC razor: conditional attribute in HTML
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
add a comment |
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
Perhaps creating a custom HTML helper that would render out the LI with child link elements?
– Nick Bork
Feb 22 '12 at 17:09
add a comment |
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
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
asp.net-mvc asp.net-mvc-3 razor
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
add a comment |
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
add a comment |
5 Answers
5
active
oldest
votes
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
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 anonymoushtmlProperties
object? E.g. I want to conditionally pass attributedisabled
, like@Html.TextBoxFor(lambda, new { disabled = condition ? true : null })
, but that still rendersdisabled=""
whendisabled
wasnull
, which is the same as rendringdisabled="anything"
becausedisabled
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
add a comment |
<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.
Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).
– ctrlplusb
Mar 15 '13 at 13:22
add a comment |
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.
1
Very elegant way for do that. But instead ofFunc<bool>
lambda, i will prefer a simplebool?
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
add a comment |
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/
add a comment |
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();
}
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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 anonymoushtmlProperties
object? E.g. I want to conditionally pass attributedisabled
, like@Html.TextBoxFor(lambda, new { disabled = condition ? true : null })
, but that still rendersdisabled=""
whendisabled
wasnull
, which is the same as rendringdisabled="anything"
becausedisabled
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
add a comment |
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
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 anonymoushtmlProperties
object? E.g. I want to conditionally pass attributedisabled
, like@Html.TextBoxFor(lambda, new { disabled = condition ? true : null })
, but that still rendersdisabled=""
whendisabled
wasnull
, which is the same as rendringdisabled="anything"
becausedisabled
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
add a comment |
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
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
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 anonymoushtmlProperties
object? E.g. I want to conditionally pass attributedisabled
, like@Html.TextBoxFor(lambda, new { disabled = condition ? true : null })
, but that still rendersdisabled=""
whendisabled
wasnull
, which is the same as rendringdisabled="anything"
becausedisabled
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
add a comment |
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 anonymoushtmlProperties
object? E.g. I want to conditionally pass attributedisabled
, like@Html.TextBoxFor(lambda, new { disabled = condition ? true : null })
, but that still rendersdisabled=""
whendisabled
wasnull
, which is the same as rendringdisabled="anything"
becausedisabled
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
add a comment |
<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.
Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).
– ctrlplusb
Mar 15 '13 at 13:22
add a comment |
<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.
Nice one, much cleaner than some of the other options (besides the Razor 2.0 option).
– ctrlplusb
Mar 15 '13 at 13:22
add a comment |
<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.
<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.
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
add a comment |
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
add a comment |
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.
1
Very elegant way for do that. But instead ofFunc<bool>
lambda, i will prefer a simplebool?
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
add a comment |
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.
1
Very elegant way for do that. But instead ofFunc<bool>
lambda, i will prefer a simplebool?
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
add a comment |
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.
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.
answered Apr 9 '14 at 20:30
defrostdefrost
33626
33626
1
Very elegant way for do that. But instead ofFunc<bool>
lambda, i will prefer a simplebool?
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
add a comment |
1
Very elegant way for do that. But instead ofFunc<bool>
lambda, i will prefer a simplebool?
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
add a comment |
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/
add a comment |
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/
add a comment |
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/
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/
answered Jan 30 '13 at 11:27
David SlavíkDavid Slavík
7321021
7321021
add a comment |
add a comment |
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();
}
}
add a comment |
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();
}
}
add a comment |
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();
}
}
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();
}
}
answered Jul 10 '18 at 6:31
Pavlo NeymanPavlo Neyman
5,61932125
5,61932125
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Perhaps creating a custom HTML helper that would render out the LI with child link elements?
– Nick Bork
Feb 22 '12 at 17:09