为什么 =ViewData[""] 显示一个字符串,但对同一字符串进行评估却失败?
//CHECK IF WE SHOULD SHOW THE PASSWORD HINT OR NOT
Setting passwordhints;
using (var db = new dbDataContext())
{
passwordhints = (from c in db.Settings
where c.Name == "ShowPasswordHints" && c.ID == _ID
select c).FirstOrDefault();
}
if (passwordhints != null)
//NOTE: .Value IS A STRING
ViewData["ShowPasswordHints"] = passwordhints.Value;
else
ViewData["ShowPasswordHints"] = "False";
//END PASSWORD HINTS CHECK
在控制器中,当我到达页面本身时,我将
<%=ViewData["ShowPasswordHints"]%>
输出到标题标签中,我可以看到它在那里显示“True” (没有引号,我还通过用括号将其括起来来检查空格,并且没有空格,它实际上就是 True)
但是,当我确实
<%if(ViewData["ShowPasswordHints"] == "True") {%> SHOW THIS <%}%>
SHOW THIS 从未出现时,到底是什么?
更新:但是,如果 ViewData 像这样设置...它可以工作...嗯?
if (accountRepository.isLDAPEnabled(_ID))
ViewData["LDAP"] = "True";
else
ViewData["LDAP"] = "False";
查看...
<%if(ViewData["LDAP"] == "True"){ %>
SHOW THIS
<%} %>
谢谢大家,这是非常有效的新方法
ViewData["something"] = true;
<%if(true.Equals(ViewData["something"])){%> SHOW THIS <%}%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
ViewData
是IDictionary
,因此ViewData["ShowPasswordHints"]
的类型为object
。默认情况下,对象
通过引用进行比较。您想要进行价值比较。因此,尝试将其转换为字符串
,这将导致值比较:更多信息请参见msdn。
更新:您放入 (返回普通对象的字典)。但既然您知道得更清楚,您可以将其转换为您知道应该是的
ViewData["ShowPasswordHints"]
中的值始终是一个字符串。然而,由于 C# 是静态类型的,编译器不知道当你把它取出来时,它是一个字符串——它只知道它将是一个对象,因为ViewData
是一个 < code>IDictionary字符串
。 (顺便说一句,我认为 ViewData 是 MVC 框架的最弱点之一,出于这个原因和其他原因)为什么这在</code> 中起作用是因为 <code><%= % ></code> 标签对其中的任何内容调用 <code>ToString()</code> 。由于 <code>ViewData["ShowPasswordHints"]</code> 是一个字符串,因此它的结果就像您所期望的那样 - 字符串的 <code>ToString()</code> 是字符串本身。
最后:为什么不使用布尔值?
Since
ViewData
is anIDictionary<string, object>
,ViewData["ShowPasswordHints"]
is of typeobject
. By default,object
s are compared by reference. You want a value comparison. Thus, try casting it to astring
, which will cause a value comparison:More at msdn.
UPDATE: The value you put into
ViewData["ShowPasswordHints"]
is always a string. However, since C# is statically typed, the compiler doesn't know that when you take it back out, it is a string -- it only knows that it will be an object, sinceViewData
is aIDictionary<string, object>
(a dictionary returning plain objects). But since you know better, you can cast it to thestring
that you know it should be. (BTW, I think ViewData is one of the weakest points of the MVC framework, for this reason and others)Why this works in the
<title>
is because the<%= %>
tags callToString()
on whatever in them. SinceViewData["ShowPasswordHints"]
is a string, it comes out like you'd expect --ToString()
of a string is the string itself.Finally: why aren't you using a boolean?