How do I construct an if statement within a MVC View

风流意气都作罢 提交于 2019-12-04 19:21:54

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4573862/how-do-i-construct-an-if-statement-within-a-mvc-view

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