asp.net-mvc – 如何在MVC视图中构造if语句

希望这个问题是快速和无痛的

我有一个mvc视图,我想根据if语句显示两个值之一.这就是我在观点本身:

<%if (model.CountryId == model.CountryId) %>
        <%= Html.Encode(model.LocalComment)%> 
        <%= Html.Encode(model.IntComment)%>

如果真实显示model.LocalComment,如果是false显示模型.IntComment.

这不能用于显示两个值.我究竟做错了什么?

解决方法

您的if语句总是评估为true.你正在测试model.CountryId是否等于model.CountryId,它始终为true:if(model.CountryId == model.CountryId).你也缺少一个else语句.应该是这样的:

<%if (model.CountryId == 1) { %>
    <%= Html.Encode(model.LocalComment) %> 
<% } else if (model.CountryId == 2) { %>
    <%= Html.Encode(model.IntComment) %>
<% } %>

显然你需要用正确的值替换1和2.

就个人而言,我将为此任务编写一个HTML帮助程序,以避免视图中的标签汤:

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;
}

然后在你的看法只是:

<%= Html.Comment() %>

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。