加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 20:50:01 所属栏目:asp.Net 来源:网络整理
导读:希望这个问题是快速和无痛的 我有一个mvc视图,我想根据if语句显示两个值之一.这就是我在观点本身: %if (model.CountryId == model.CountryId) % %= Html.Encode(model.LocalComment)% %= Html.Encode(model.IntComment)% 如果真实显示model.LocalComment,如
希望这个问题是快速和无痛的

我有一个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() %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读