Я создаю Приложение Asp.net. Я должен сохранить HashTable на сессии.
При загрузке страницы я пишу
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
Здесь проблема, когда пользователь обновляет страницу, сессия ["AttemptCount"] также обновляется. Я хочу знать, где я должен объявить
Session["AttemptCount"]=new Hashtable();
Так, чтобы мои seesion не получали refeshed.
РЕДАКТИРОВАНИЕ В Global.asax, эта сессия начнет, как только пользователь открывает веб-сайт. Я хочу создать эту сессию, только если пользователь переходит к конкретной странице. т.е. Login.aspx
Сделайте это в методе Session_Start
в вашем Global.asax вот так ...
protected void Session_Start(object sender, EventArgs e)
{
Session["AttemptCount"]=new Hashtable();
}
Обновление:
Затем просто проверьте, есть ли сеанс переменная существует, если это не так, только тогда создайте переменную. Вы можете вставить его в свойство, чтобы все было чище, вот так ...
public Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"]=new Hashtable();
return Session["AttemptCount"];
}
}
А затем вы можете просто вызвать свойство AttemptCount
где угодно, вот так ...
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
Мой последний интерес касается робототехники. Вы можете получить микроконтроллер примерно за $30 (arduino.cc) - и различные двигатели от E-bay. Еще у меня есть несколько дешевых дальномеров и GPS-приемник - каждый из них под $30...
Я также создаю веб-приложения. Я не очень устал от этого, но все свободное время я провожу программирование в C.
-121--4585686-В Java с использованием рекурсии:
import java.util.LinkedList;
import java.util.List;
public class Main {
// Number-to-letter mappings in order from zero to nine
public static String mappings[][] = {
{"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
{"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"},
{"T", "U", "V"}, {"W", "X", "Y", "Z"}
};
public static void generateCombosHelper(List<String> combos,
String prefix, String remaining) {
// The current digit we are working with
int digit = Integer.parseInt(remaining.substring(0, 1));
if (remaining.length() == 1) {
// We have reached the last digit in the phone number, so add
// all possible prefix-digit combinations to the list
for (int i = 0; i < mappings[digit].length; i++) {
combos.add(prefix + mappings[digit][i]);
}
} else {
// Recursively call this method with each possible new
// prefix and the remaining part of the phone number.
for (int i = 0; i < mappings[digit].length; i++) {
generateCombosHelper(combos, prefix + mappings[digit][i],
remaining.substring(1));
}
}
}
public static List<String> generateCombos(String phoneNumber) {
// This will hold the final list of combinations
List<String> combos = new LinkedList<String>();
// Call the helper method with an empty prefix and the entire
// phone number as the remaining part.
generateCombosHelper(combos, "", phoneNumber);
return combos;
}
public static void main(String[] args) {
String phone = "3456789";
List<String> combos = generateCombos(phone);
for (String s : combos) {
System.out.println(s);
}
}
}
-121--990580- проверьте, существует ли она в первую очередь
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if(Session["AttemptCount"] == null)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
}
, хотя session_start лучше, ее необходимо использовать только на одной странице, но ее можно создать для каждого сеанса.
Посмотрите на Global .asax и Application_Started (я думаю), и есть один для запуска сеанса.
Вы можете сделать такое свойство в вашей странице:
protected Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"] = new Hashtable();
return Session["AttemptCount"] as Hashtable;
}
}
тогда вы сможете использовать его без проблем:
protected void Page_Load(object sender, EventArgs e)
{
this.AttemptCount.Add("key", "value");
}