简体   繁体   English

如何在 mvc 控制器中写入数据?

[英]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.

相关问题 如何使用 HttpWebRequest 将数据发布到 MVC Controller? - How do I post data to MVC Controller using HttpWebRequest? 如何使用传递的字符串参数从控制器编写MVC实体框架选择查询? - How do I write an MVC Entity Framework select query from the controller using passed string arguments? 如何通过代码禁用MVC控制器? - How do I disable an MVC controller by code? 当我不知道JSON对象名称时,如何在MVC控制器中获取JSON数据? - How do I get the JSON data in my MVC controller, when I dont know the JSON object name? 使用模式模板和JavaScript时如何将数据传递到MVC控制器 - How do i pass data to mvc controller when using a modal template and javascript 如何将数据从Select2选项/值(标签)获取到ASP.NET MVC中的控制器? - How do I get the data from a Select2 options/value (tags) to the controller in asp.net mvc? 如何将数据从asp.net MVC控制器发布到非MVC asp.net页面? - How do I POST data from an asp.net MVC controller to a non-MVC asp.net page? 如何通过Ajax将复杂对象发布到MVC 4控制器? - How do I post a complex object to an MVC 4 controller via Ajax? 如何在MVC Core中动态选择控制器 - How do I dynamically choose a controller in MVC Core 我如何从下拉列表中选择值到模式或控制器MVC - how do i select value from dropdownlist to mode or to controller mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM