Asp.net-Mvc

如何在 MVC 視圖中構造 if 語句

  • February 18, 2013

希望這個問題快速而輕鬆

我有一個 mvc 視圖,我想根據 if 語句顯示兩個值之一。這就是我在視圖本身中所擁有的:

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

如果為 true 則顯示 model.LocalComment,如果為 false 則顯示 model.IntComment。

這不起作用,因為我得到了兩個值。我究竟做錯了什麼?

你的if陳述總是評估為真。您正在測試model.CountryIdequalsmodel.CountryId是否始終為真: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() %>

引用自:https://stackoverflow.com/questions/4573862