Cunners
Cunners

Reputation: 1286

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?

Upvotes: 9

Views: 19594

Answers (3)

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

Conditional Rendering in Asp.Net MVC Views

 <% if(customer.Type == CustomerType.Affiliate) %>
   <%= this.Html.Image("~/Content/Images/customer_affiliate_icon.jpg")%>
 <% else if(customer.Type == CustomerType.Preferred) %>
   <%= this.Html.Image("~/Content/Images/customer_preferred_icon.jpg")%>
 <% else %>
   <%= this.Html.Image("~/Content/Images/customer_regular_icon.jpg")%>  

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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() %>

Upvotes: 11

Jon Skeet
Jon Skeet

Reputation: 1504162

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

Upvotes: 6

Related Questions