I have a search function on my site, and one of the options the user has is to select the type of search.
So given this example in a view:
@using System.Data
@model DataSet
hello, world
<br />
@ViewData["searchtype"]
@if (ViewData["searchtype"] == "rank")
{
<h2>Ranks</h2>
<ol>
@foreach (DataRow dr in Model.Tables[0].Rows)
{
<li>@dr["name"].ToString()</li>
}
</ol>
}
I would expect it to either give me the header Ranks by itself (if the datatable is empty) or a numbered list of ranks following that header.
What I get instead is this:
hello, world
rank
So I know that it's getting to the view. And I know that it's able to see the value of the ViewData["searchtype"]
. But the conditional, which should be evaluated as true, is not.
And I know that the obvious answer is for ViewData["searchtype"]
to be changed to ViewData["searchtype"].ToString()
, but when I do that, I get literally nothing. No "hello, world", no "rank", no "Rank", and nothing from the _Layout page, either. Just a pristine blank browser.
Also, I'm aware that using a DataSet as a model instead of an object is not optimal, but the data tables generated differ depending on the search type, so I'm stuck with that.
To expand on @Jackdaw's answer, Microsoft's pattern matching documentation for the is
operator lists:
C# supports multiple patterns, including declaration, type, constant, relational, property, list, var, and discard.
Under the section Constant pattern:
You use a constant pattern to test if an expression result equals a specified constant. ... you can use any constant expression, such as ... an
integer
orfloating-point
numerical literal, astring
literal, a Boolean valuetrue
orfalse
, ...
In your post, you're comparing against the string literal "rack"
so you can set your if
condition to:
@if (ViewData["searchtype"] is "rank")
{
...
}
As the comments (see @ProgrammingLlama's comment) and answer (from @Akade) in this SO post emphasizes, ensure the use of a string
literal versus a string
variable.
If the "searchtype" key is not in the ViewData
dictionary or the key is in the dictionary but its value is explicitly set to null
, or the "searchtype" key/value pair is some other value, then the if
condition above evaluates to false
.
@Jackdaw's answer uses the is
operator to match an expression against the pattern listed under the section Declaration and type patterns:
When a declaration pattern matches an expression, that variable is assigned a converted expression result