asp.net-mvc – 如何在MVC视图中构造if语句
发布时间:2020-09-21 14:37:11 所属栏目:asp.Net 来源:互联网
导读:希望这个问题是快速和无痛的 我有一个mvc视图,我想根据if语句显示两个值之一.这就是我在观点本身: %if (model.CountryId == model.CountryId) % %= Html.Encode(model.LocalComment)% %= Html.Encode(model.IntComment)% 如果真实显示model.L
希望这个问题是快速和无痛的 我有一个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() %> (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |