简体   繁体   中英

How do I write data in mvc controller?

I faced a problem; it is necessary to read data from the devices using the modbus protocol. I can not understand how to write to database in ActionResult. Maybe someone can help.

 public ActionResult Index(Sensors sensors)
    {

        Sensors snsr = new Sensors();


        client = new ModbusClient(IpAddress, port);
        client.Connect();

        int[] response = client.ReadHoldingRegisters(StartAddress, quantity);
        client.Disconnect();

        for (int i = 0; i < quantity; i++)
        {
            string value0 = response[0].ToString();
            string value1 = response[1].ToString();
            string value2 = response[2].ToString();
            ViewBag.stohome0 = value0;
            ViewBag.stohome1 = value1;
            ViewBag.stohome2 = value2;
            snsr.sensorname = response[0];
            db.Sensors.Add(snsr);
            db.SaveChanges();


        }

        return View();

You need to create a new Sensors object for every time that the for -loop executes its body.

I tried to make things more clear by constructing a unique name for each sensor, instead of using the response[...] value for that. And I gave a suggestion of how to use the response[...] values.

for (int i = 0; i < quantity; i++)
{
    Sensors snsr = new Sensors();
    snsr.sensorname = "Sensor-" + i;

    // Maybe also do something like...
    // snsr.sensorvalue = response[i];

    db.Sensors.Add(snsr);
    db.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM