使用同一类存储多次运行的数据

问题描述 投票:0回答:1

在我的项目中,我有一个ajax方法,它会多次触发一个函数(一次都运行一次)。例如,如果用户按下一个按钮,它将触发Ajax,并且该函数将获取数据10秒钟。此后,用户可以再次按下该按钮,这将再次触发Ajax方法,并将获取10的更多数据,依此类推。在每个触发器上,我都必须以某种方式存储此数据,并且在所有运行结束时,我将合并并存储在数据库中。

我的问题是,如果我创建一个包含所有运行时的类,则每当我输入此函数时,都会重新初始化丢失先前数据的类。所以我现在的想法是:

我这样称呼一个函数:前端侧:

function ReadsSerial() {
        $.ajax({
            url: "/Home/ReadsSerial",
            type: 'POST',
            data: { sintraining: gTrained },
            success: function (result) {
                alert(result.name);
            },
            error: function () {
                alert("error");
            }
        });
        return false;
};

在我的后端,我有一个像这样的功能:

[HttpPost]
        public ActionResult ReadsSerial(string sintraining)
        {
            try
            {
                sintraining = Int32.Parse(sintraining);
            }
            catch (FormatException)
            {
                Console.WriteLine($"Unable to parse '{sintraining}'");
            }

                if (sintraining == 0)
                {
                    // Call the constructor that has no parameters.
                    HandGesturesStorage0 handGesturesStorage = new HandGesturesStorage0();
                    handGesturesStorage.HandGesture0 = all;
                }
                if (sintraining == 1)
                {
                    HandGesturesStorage1 handGesturesStorage = new HandGesturesStorage1();
                    handGesturesStorage.HandGesture1 = all;
                }
                if (sintraining == 2)
                {
                    HandGesturesStorage2 handGesturesStorage = new HandGesturesStorage2();
                    handGesturesStorage.HandGesture2 = all;
                }

我的班级是这样的:

public class HandGesturesStorage0
{
    public string HandGesture0 { get; set; }
}

public class HandGesturesStorage1
{
    public string HandGesture1 { get; set; }
}

public class HandGesturesStorage2
{
    public string HandGesture2 { get; set; }
}

但是我觉得这一定是更好的方法!如果我有10个运行时间,则必须创建10个else和10个类。有什么想法吗?

c# asp.net class asp.net-ajax
1个回答
0
投票
    static List<HandGesturesStorage> myStogae;

    [HttpPost]
    public ActionResult ReadsSerial(string sintraining)
    {
        if (myStogae == null)
        {
            myStogae = new List<HandGesturesStorage>();
        }

        int st;

        try
        {
            st = Int32.Parse(sintraining);
            myStogae.Add(new HandGesturesStorage(sintraining));
        }
        catch (FormatException)
        {
            Console.WriteLine("Unable to parse '{sintraining}'");
        }
    }

    public class HandGesturesStorage
    {
        public string HandGesture { get; set; }

        public HandGesturesStorage(string sintraining)
        {
            this.HandGesture = sintraining;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.