How do I construct an if statement within a MVC View

孤街醉人 提交于 2019-12-03 12:23:17

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

Jahan Zinedine

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")%>  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!