简体   繁体   English

如何检查查询字符串是否为空

[英]How to check if the query string is null

I am querying a table using C# and produce the following SQL line: 我正在使用C#查询表并产生以下SQL行:

'det.aspx?ObjectID=' + CAST(CT.OBJECTID AS VARCHAR) + '&cid=45&fid=' + ISNULL(CAST(CT.A0900 AS VARCHAR), '') 'TD'

produces: 产生:

http://localhost:3652/Pages/det.aspx?ObjectID=1092648&cid=45&fid=

I am trying to get the value for fid ONLY if it is not null OR if there is a value: 我试图只获取fid的值(如果它不为null或有值):

if (Request.QueryString["fid"] != null || Request.QueryString["fid"].Length > 0)
{
    string t = Request.QueryString["fid"];
}

Using the example above, it should not enter the if caluse, but it is. 使用上面的示例,它不应输入if caluse,而应输入。

How can I resolve it. 我该如何解决。

change your query to this: (use a case statement inside it) 将查询更改为此:(在其中使用case语句)

'det.aspx?ObjectID=' + CAST(CT.OBJECTID AS VARCHAR) + '&cid=45'+

case when CT.A0900 is not null then '&fid='+CAST(CT.A0900 AS VARCHAR)
else '' end

When checking for a null or empty string, use the built-in .NET string method of string.IsNullOrEmpty or string.IsNullOrWhiteSpace : 检查空字符串或空字符串时,请使用内置的.NET字符串方法string.IsNullOrEmptystring.IsNullOrWhiteSpace

if ( !string.IsNullOrWhiteSpace(Request.QueryString["fid"]) )
{
    string t = Request.QueryString["fid"];
}

This condition will succeed when the string is empty because of the or statement. 当字符串由于or语句而为空时,此条件将成功。 Note that empty is not the same as null: 请注意,empty与null不相同:

if (Request.QueryString["fid"] != null || Request.QueryString["fid"].Length > 0)
{
    // "fid" could be empty, not null which causes the first condition to succeed.
    string t = Request.QueryString["fid"];
}

You'd want to use an && statement in the above: 您想在上面使用&&语句:

if (Request.QueryString["fid"] != null && Request.QueryString["fid"].Trim().Length > 0)
{
    string t = Request.QueryString["fid"];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM