[英]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.
需要使用 modbus 协议从设备读取数据。 I can not understand how to write to database in ActionResult.
我无法理解如何在 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.每次
for
循环执行其主体时,您都需要创建一个新的Sensors
对象。
I tried to make things more clear by constructing a unique name for each sensor, instead of using the response[...] value for that.我试图通过为每个传感器构建一个唯一的名称来使事情更清楚,而不是使用 response[...] 值。 And I gave a suggestion of how to use the response[...] values.
我就如何使用 response[...] 值提出了建议。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.