Hopefully this question is quick and painless
I have a mvc view where i want to display either one of two values depending on an if statement. This is what I have in the view itself:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
If true display model.LocalComment, if false display model.IntComment.
This doesn't work as I get both values showing. What am I doing wrong?
To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.
Your if
statement always evaluates to true. You are testing whether model.CountryId
equals model.CountryId
which is always true: if (model.CountryId == model.CountryId)
. Also you are missing an else
statement. It should be like this:
<%if (model.CountryId == 1) { %>
<%= Html.Encode(model.LocalComment) %>
<% } else if (model.CountryId == 2) { %>
<%= Html.Encode(model.IntComment) %>
<% } %>
Obviously you need to replace 1
and 2
with the proper values.
Personally I would write an HTML helper for this task to avoid the tag soup in the views:
public static MvcHtmlString Comment(this HtmlHelper<YourModelType> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model.CountryId == 1)
{
return MvcHtmlString.Create(model.LocalComment);
}
else if (model.CountryId == 2)
{
return MvcHtmlString.Create(model.IntComment);
}
return MvcHtmlString.Empty;
}
And then in your view simply:
<%= Html.Comment() %>
Aside from Darin's point about the condition always being true, you might want to consider using the conditional operator:
<%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
(Adjust for whatever your real condition would be, of course.)
Personally I find this easier to read than the big mixture of <% %>
and <%= %>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With