如何从字典会话中获取价值 [英] How to get value from dictionary session
本文介绍了如何从字典会话中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在会话中使用如下字典存储了多个值
< pre> var get_values = new Dictionary< string,object>();
get_values [name] = model.Name; ;
get_values [address] = model.Address;
get_values [phone] = model.Phone;
get_values [email] = model.Email;
会话[sess_values] = get_values;
现在我想获得价值从会议一个接一个。我的问题是如何从名称,地址等会话中获取价值?
我尝试了什么:
< pre>< pre> var get_values = new Dictionary< string,object>();
get_values [name] = model.Name; ;
get_values [address] = model.Address;
get_values [phone] = model.Phone;
get_values [email] = model.Email;
会话[sess_values] = get_values;
解决方案
尝试:字典<字符串,字符串> values =会话[ sess_values] as 字典< string,string> ;;
if (values!= null )
{
string name = values [ name];
...
简单:从会话中检索字典;如果它不为null,请尝试从字典中检索值。
var values =(Dictionary< string,object>)Session [ sess_values];
if (values!= null )
{
object value ;
if (values.TryGetValue( name , out value ))
{
string s = value as 串跨度>;
if (s!= null )
{
model。名字= s;
}
}
}
如果您使用的是最新版本的Visual Studio,可以稍微简化一下:
var values =(Dictionary< string,object>)Session [ sess_values];
if (values?.TryGetValue( 名称, out object value )&& value string s)
{
model.Name = s;
}
但为什么你使用字典< TKey,TValue>
并不明显首先,当你可以直接使用会话时:
会话[ name] = model.Name;
model.Name =( string )会话[ 名跨度>];
i have stored multiple values in session using dictionary like below
<pre> var get_values = new Dictionary<string, object>(); get_values["name"] = model.Name; ; get_values["address"] = model.Address; get_values["phone"] = model.Phone; get_values["email"] = model.Email; Session["sess_values"] = get_values;
now i want to get values from session one by one. my question is how to get values from session like name, address etc.?
What I have tried:
<pre><pre> var get_values = new Dictionary<string, object>(); get_values["name"] = model.Name; ; get_values["address"] = model.Address; get_values["phone"] = model.Phone; get_values["email"] = model.Email; Session["sess_values"] = get_values;
解决方案
Try:Dictionary<string, string> values = Session["sess_values"] as Dictionary<string, string>; if (values != null) { string name = values["name"]; ...
Simple: retrieve the dictionary from the session; if it's not null, try to retrieve the value from the dictionary.
var values = (Dictionary<string, object>)Session["sess_values"]; if (values != null) { object value; if (values.TryGetValue("name", out value)) { string s = value as string; if (s != null) { model.Name = s; } } }
If you're using a recent version of Visual Studio, you can simplify that slightly:
var values = (Dictionary<string, object>)Session["sess_values"]; if (values?.TryGetValue("name", out object value) && value is string s) { model.Name = s; }
But it's not obvious why you're using aDictionary<TKey, TValue>
in the first place, when you could just use the session directly:
Session["name"] = model.Name; model.Name = (string)Session["name"];
这篇关于如何从字典会话中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文