Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct an if statement within a MVC View

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?

like image 224
Cunners Avatar asked Jan 01 '11 11:01

Cunners


People also ask

Can I declare variable in view MVC?

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.

What is Razor syntax in MVC?

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.


2 Answers

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() %>
like image 147
Darin Dimitrov Avatar answered Oct 23 '22 06:10

Darin Dimitrov


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 <%= %>.

like image 29
Jon Skeet Avatar answered Oct 23 '22 07:10

Jon Skeet