Update DIV with Ajax Asp.Net C#

Asked

Viewed 601 times

1

I’m setting up a Dashboard for tracking tickets, in it there are basically two things, 4 fields and 1 chart. I would like to update them periodically, tried with

<meta http-equiv="refresh" content="10" />

However, this recharges the entire page, generating that famous blink. What I need is to reload the fields and graph without this refresh (blinked). From what I found on the internet, I can do this with AJAX, but I don’t know how, I’m still starting with development.

Not to get too big a code, then follow my page with only 1 field, and the chart:

@using System.Data
@model DataSet

@{ ViewBag.Title = "Home Page";}


<!-- container-fluid -->
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="row">
        <div class="col-lg-12">
            <h2 class="page-header">
                Tickets AGP
            </h2>
        </div>
    </div>
    <!-- /Page Heading -->


    <!-- Campos -->
    <div class="row">
        <div class="col-lg-3 col-md-6">
            <div class="panel panel-danger">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-xs-3">
                            <i class="fa fa-tasks fa-5x"></i>
                        </div>
                        <div class="col-xs-9 text-right">

                            <div class="huge">

                                @foreach (DataRow row in Model.Tables[1].Rows)
                                {

                                    if (@row["status"].Equals("Aberto - Aguardando Aprovação"))
                                    {
                                        @row["quantidade_status"]
                                    }
                                }

                            </div>
                            <div>Aguardando Aprovação</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- /Campos -->


    <!-- Gráficos Morris Charts -->
    <div class="row">

        <div class="col-lg-6">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="fa fa-long-arrow-right"></i> Atendimento AGP</h3>
                </div>
                <div class="panel-body">
                    <div id="morris-bar-agp"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /container-fluid -->

@section scripts {

    <!-- Script que carrega as informacoes do grafico-->
    <script>

    $(document).ready(function (){

        $.get('@Url.Action("GetData", "Home")', function (data) {
            console.log(data);


            Morris.Bar({

                element: 'morris-bar-agp',
                xkey: 'admAtribuido',
                ykeys: ['quantidade_admAtribuido'],
                labels: ['Tickets Atendidos'],
                barRatio: 0.4,
                xLabelAngle: 10,
                gridTextSize: 12,
                gridTextColor: '#000',
                hideHover: 'auto',
                resize: true,
                data: data
            });

            $(window).trigger('resize');
            $('svg').height(650);

            });
    });

    </script>
}

[EDIT] Follow Action Getdata(), I believe that the query is not important in this case, so I put this generic there, because mine is very large:

[HttpGet]
    public JsonResult GetData()
    {

        DataSet ds = new DataSet();
        using (SqlConnection con = new SqlConnection("Data Source=xxx.xx.xxx.xxx;Initial Catalog=XXX;User ID=xxxxxx;Password=xxxxx"))
        {

         string query = select * from table

         using (SqlCommand cmd = new SqlCommand(query))
         {
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(ds);
                }

            }
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[2]);

            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json, (new[] { new { admAtribuido = "", quantidade_admAtribuido = 0 } }).GetType());

            return Json(obj, JsonRequestBehavior.AllowGet);
        }
    } 

Follow the Action Index() which sends the data of the fields to be recovered in the View:

public ActionResult Index()
    {
        DataSet ds = new DataSet();

        using (SqlConnection con = new SqlConnection("Data Source=xxx.xx.xxx.xxx;Initial Catalog=XXX;User ID=xxxxxx;Password=xxxxxx"))
        {
            query select * from table

        using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {

                    sda.Fill(ds);
                }
            }
        }

        return View(ds);
    }
  • Place next to the question, your action GetData(). You need to have an action that returns only the content-relevant data you need to update and preferably in Json.

  • Opa, I will put, but this so msm as you said, returning a JSON only with the information I need....

1 answer

0

You can use javascript’s Setinterval function, which will make your code repeat from time to time as defined.

setInterval(function(){
    $.get('@Url.Action("GetData", "Home")', function (data) {
                console.log(data);


                Morris.Bar({

                    element: 'morris-bar-agp',
                    xkey: 'admAtribuido',
                    ykeys: ['quantidade_admAtribuido'],
                    labels: ['Tickets Atendidos'],
                    barRatio: 0.4,
                    xLabelAngle: 10,
                    gridTextSize: 12,
                    gridTextColor: '#000',
                    hideHover: 'auto',
                    resize: true,
                    data: data
                });

                $(window).trigger('resize');
                $('svg').height(650);

                });
        });
}, 1000);

The function signature is defined as setInterval(function, milliseconds);, in the example, the code within the parameter function will run every thousand milliseconds, which would be every 1 second.

See an example on w3schools

Browser other questions tagged

You are not signed in. Login or sign up in order to post.