开发者

updating a variable in an ASP.NET MVC view

开发者 https://www.devze.com 2023-03-28 13:36 出处:网络
I have this string variable call \"status\" which is updated by a serial port connection I\'ve made. the \"status\" show\'s if u are connected to the serial port or not.

I have this string variable call "status" which is updated by a serial port connection I've made. the "status" show's if u are connected to the serial port or not. I've made a simple 2 buttons view. one opens the connection and the other close it. i want to be able to auto update the status of the connection inside the view. i guess i need to use some kind of timer which shows the string inside "status" every given time, but i have no clue on how to do it..

This is my HomeController:

public class HomeController : Controller
{   
   public ActionResult Index()
    {
      return View();
    }

    [HttpPost]
    public JsonResult CheckStatus()
    {
    return Json(new { status = "active" });
    }
}

and this is my view:

<script type="text/javascript">
$(function() {
    // poll every 5 seconds
    setInterval('checkStatus()', 5000开发者_如何学编程);
}

function checkStatus() {
    $.ajax({
        url: 'Home/CheckStatus',
        type: 'POST',
        dataType: 'json',
        success: function(xhr_data) {
            if(xhr_data.status == 'active') {
                // this would just disable the "Open" button
                $('#btnOpen').attr('disabled', 'disabled');
            }
        }
    });
}


I'm going to assume you can use jQuery, and that you have a Controller action that looks like this:

[HttpPost]
public class StatusController : Controller
{
    public JsonResult CheckStatus()
    {
        return Json(new { status = "active" });
    }
}

Then, in your view add the following script

<script type="text/javascript">
    $(function() {
        // poll every 5 seconds
        setInterval('checkStatus()', 5000);
    }

    function checkStatus() {
        $.ajax({
            url: 'Status/CheckStatus',
            type: 'POST',
            dataType: 'json',
            success: function(xhr_data) {
                if(xhr_data.status == 'active') {
                    // this would just disable the "Open" button
                    $('#btnOpen').attr('disabled', 'disabled');
                }
            }
        });
    }
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消