Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / Получение объекта по id из коллекции IDictionary / 3 сообщений из 3, страница 1 из 1
30.08.2016, 18:03
    #39300514
Anton19
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Получение объекта по id из коллекции IDictionary
Есть абстрактный класс, наследник и контроллер. Мне в строке "ViewBag.Text = devicesDictionary[id].Status; // Не могу здесь вывести состояние объекта [id] студия подчеркивает красным The name 'id' does not exist in the current context" необходимо вывести строковое значение статуса. Но devicesDictionary[id].Status не могу применить. Как можно решить вывод строки? На веб-формах у меня было так:
Код: c#
1.
 IDictionary<int, Device> devicesDictionary; private int id; public void DeviceControl(int id, IDictionary<int, Device> devicesDictionary) { this.id = id; this.devicesDictionary = devicesDictionary; Initialize(); }

Как аналогично сделать на MVC?

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
public abstract class Device : IStatus
{
    private bool status;
    public Device()
    {

    }
    public Device(bool status, string name)
    {
        Status = status;
        Name = name;
    }
    public string Name { get; set; }
    public bool Status
    {
        get
        {
            return status;
        }
        set
        {
            status = value;
        }
    }
    public virtual void OnDevice()
    {
        if (Status == false)
        {
            status = true;
        }
    }
    public virtual void OffDevice()
    {
        if (Status)
        {
            status = false;
        }
    }
    public override string ToString()
    {
        string status;
        if (this.status)
        {
            status = "Включено";
        }
        else
        {
            status = "Выключено";
        }
        return status;
    }
}   
  public class Lamp : Device, ILampMode
{
    private BrightnessLevel level;
    public Lamp(bool status, string name, BrightnessLevel level)
        : base(status, name)
    {
        this.level = level;
    }
    public BrightnessLevel Level
    {
        get
        {
            return level;
        }
    }
    public void SetLowBrightness()
    {
        if (Status)
        {
            level = BrightnessLevel.Low;
        }
    }
    public void SetMediumBrightness()
    {
        if (Status)
        {
            level = BrightnessLevel.Medium;
        }
    }
    public void SetHighBrightness()
    {
        if (Status)
        {
            level = BrightnessLevel.High;
        }
    }
    public override string ToString()
    {
        string mod;
        if (level == BrightnessLevel.Low)
        {
            mod = "Низкий";
        }
        else if (level == BrightnessLevel.Medium)
        {
            mod = "Средний";
        }
        else if (level == BrightnessLevel.High)
        {
            mod = "Высокий";
        }
        else
        {
            mod = "Не задан";
        }
        return base.ToString() + "
" + "Режим яркости: " + mod.ToString();
    }
}   
  public ActionResult Index()
          {
        IDictionary<int, Device> devicesDictionary;
        if (Session["Devices"] == null)
        {
            devicesDictionary = new SortedDictionary<int, Device>();
            devicesDictionary.Add(1, new Lamp(false, "Лампа", BrightnessLevel.High));
            Session["Devices"] = devicesDictionary;
            Session["NextId"] = 2;
        }
        else
        {
            devicesDictionary = (SortedDictionary<int, Device>)Session["Devices"];
        }

        SelectListItem[] devicesList = new SelectListItem[1];
        devicesList[0] = new SelectListItem { Text = "Лампа", Value = "lamp", Selected = true };
        ViewBag.DevicesList = devicesList;
        ViewBag.Text = devicesDictionary[id].Status; // Не могу здесь вывести состояние объекта
        return View(devicesDictionary);
    }
...
Рейтинг: 0 / 0
30.08.2016, 21:24
    #39300655
fsharp_fsharp
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Получение объекта по id из коллекции IDictionary
попытайтесь изложить суть проблемы яснее. читать весь это код не хочется
...
Рейтинг: 0 / 0
31.08.2016, 08:36
    #39300784
skyANA
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Получение объекта по id из коллекции IDictionary
Anton19, проблема у Вас в том, что раньше в коде была определена переменная id и откуда-то приходило её значение.
Сейчас ни переменной, ни значения.

А чтобы что-то подсказать, хотелось бы толком описанную задачу увидеть, а не какие-то попытки её решения.
...
Рейтинг: 0 / 0
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / Получение объекта по id из коллекции IDictionary / 3 сообщений из 3, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]