我在我的视图中使用以下代码来检查是否存在查询参数,例如 domain.com/?query=moo
if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code }
但现在需要更改它,以便检查 ViewData 查询参数是否存在,但不太确定如何重新编写。我的 ViewData 如下所示:ViewData["query"]
有人能帮忙吗?谢谢
我在我的视图中使用以下代码来检查是否存在查询参数,例如 domain.com/?query=moo
if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code }
但现在需要更改它,以便检查 ViewData 查询参数是否存在,但不太确定如何重新编写。我的 ViewData 如下所示:ViewData["query"]
有人能帮忙吗?谢谢
if (ViewData["query"] != null)
{
// your code
}
如果你非常需要获取一个字符串值,可以这样做:
string query = (ViewData["query"] ?? string.Empty) as string;
if (!string.IsNullOrEmpty(query))
{
// your code
}
在Hunter的回答基础上,进一步解释一下...
ViewData
Dictionary
是一个非常自由的类型。
检查数值是否存在的最简单方法(Hunter给出的第一个例子)是:
if (ViewData.ContainsKey("query"))
{
// your code
}
public static class ViewDataExtensions
{
public static T ItemCastOrDefault<T>(this ViewDataDictionary that, string key)
{
var value = that[key];
if (value == null)
return default(T);
else
return (T)value;
}
}
String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))
但一般来说,我喜欢将这些检查封装在表达意图明确的扩展方法中,例如:
public static class ViewDataQueryExtensions
{
const string Key = "query";
public static bool IncludesQuery(this ViewDataDictionary that)
{
return that.ContainsKey("query");
}
public static string Query(this ViewDataDictionary that)
{
return that.ItemCastOrDefault<string>(Key) ?? string.Empty;
}
}
这可以实现以下功能:
@if(ViewData.IncludesQuery())
{
...
var q = ViewData.Query();
}
public static class ViewDataDevExpressExtensions
{
const string Key = "IncludeDexExpressScriptMountainOnPage";
public static bool IndicatesDevExpressScriptsShouldBeIncludedOnThisPage(this ViewDataDictionary that)
{
return that.ItemCastOrDefault<bool>(Key);
}
public static void VerifyActionIncludedDevExpressScripts(this ViewDataDictionary that)
{
if (!that.IndicatesDevExpressScriptsShouldBeIncludedOnThisPage())
throw new InvalidOperationException("Actions relying on this View need to trigger scripts being rendered earlier via this.ActionRequiresDevExpressScripts()");
}
public static void ActionRequiresDevExpressScripts(this Controller that)
{
that.ViewData[Key] = true;
}
}
<% if(ViewData["query"]!=null)
{
if((!string.IsNullOrEmpty(ViewData["query"].ToString()))
{
//code
}
}
%>
ViewData["query"] == null
,这将会出错。很多人试图对空值进行 ToString()
操作... 很多人都会出错。 - hunterViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "What I'm looking for"
我正在尝试使用ViewData来确定当前操作是否需要在我的导航栏中处于活动状态。
<li class="@(ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "Configuration" ? "active" : null)">
as
(并扩展了此答案,提供了执行此操作的扩展:https://dev59.com/4G445IYBdhLWcg3w0dZD#35131514)。 - Ruben Bartelink