ASP.NET 内联表达式中的 DBNull 到 String 存在转换错误
大家好,我的数据库中的一个表有一个允许为空的“描述”字段。这会在 ASP.NET 中渲染页面时出现问题,因为我想确保在字符串从数据库中出来时对其进行解码,因为我在传入数据库时对其进行编码。自然地,描述中存在一些 NULL领域,我想保留。
所以我的 ASP.NET 页面有这段代码
<asp:TextBox ID="DescInfo" Text='<%# HttpUtility.HtmlDecode((string)Eval("Description")) %>' />
所以当我渲染页面时,我会得到:
Unable to cast object of type 'System.DBNull' to type 'System.String'.
我的看法,我有两个选择:
- 在加载期间绑定
或
- 使表成为非 NULL 表并使用空值
按照 也许是更好的主意?
Hey guys, a table in my database has a field "Description" that Allow's Nulls'. This causes a problem when rendering the page in ASP.NET since I want to make sure I'm decoding the string as its coming out of the database as I'm encoding it on the way in. Naturally there are some NULL's in the Description field, which I would like to keep.
So my ASP.NET page has this code
<asp:TextBox ID="DescInfo" Text='<%# HttpUtility.HtmlDecode((string)Eval("Description")) %>' />
So when I render the page, I will get:
Unable to cast object of type 'System.DBNull' to type 'System.String'.
The way I look at it, I have two options:
- bind during load
OR
- make the table a non NULL table and use empty values instead
Anyone have a better idea perhaps?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然
DBNull
无法转换为字符串,但它有一个ToString()
方法,可以返回空字符串。我可能会这样做:这样你就不必测试
DBNull
或任何东西。String.ToString()
仅返回字符串,DBNull.ToString()
返回空字符串。这还有一个优点,即每行仅调用Eval
一次,而不是两次。唯一可能让您陷入困境的是,如果您的数据同时包含null
和DBNull
(您不能在null
上调用 ToString,但您可以在DBNull
上),但我认为在这种情况下这实际上是不可能的。While
DBNull
cannot be cast to a string, it does have aToString()
method that returns an empty string. I might do it like this:That way you don't have to test for
DBNull
or anything.String.ToString()
just returns the string, andDBNull.ToString()
returns an empty string. This also has the advantage of only callingEval
one time per row instead of twice. The only thing that could trip you up is if your data contains bothnull
andDBNull
(you can't call ToString onnull
but you can onDBNull
) but I don't think that's actually possible in this case.您可以将 (string)Eval("Description") 替换为:
(Eval("Description") is System.DBNull) ? String.Empty : Eval("描述")
You could replace (string)Eval("Description") with:
(Eval("Description") is System.DBNull) ? String.Empty : Eval("Description")
您需要首先检查该值是否为空。您可以使用IsDBNull() 检查空值。
你可以使用
You need to first check if the value is a null. You can use IsDBNull() to check for nulls.
You could use
像这样的东西应该有效。我还没有给你测试过。
Something like this should work. I haven't tested it for you.