简体   繁体   中英

How to check if the query string is null

I am querying a table using C# and produce the following SQL line:

'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:

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.

How can I resolve it.

change your query to this: (use a case statement inside it)

'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 :

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. Note that empty is not the same as 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"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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