0

I am developing a MVC application website and have hit a snag, I have written a function on my HomeController called "AlertCheckFunction" That is supposed to check for certain criteria then and add messages to a list of strings then add this list to ViewBag.Message and that is outputed in a HTML View. I am trying to write a Jquery function that is set on a timer so that these alerts will recheck criteria every certain number of seconds and it will reoutput these to my automatic ticker in jquery.

Line 138-138 is my automatic ticker, and it works great when it put text in an unordered list in the html, but I can't get anything to output when I call viewbag with Razor. Line 141-162 is all my different attempts at setting up a timer query function then calling my c# function, I have gotten an alert box to work on a timer.

but I cannot figure out how to call the function properly. Link of Problem

$(document).ready(function () {
        $('.dropdown-toggle').dropdown();
        $('.dropdown-toggle').click(function (e) {
            e.stopPropagation();
            e.preventDefault();
            });
        });        

        function tick() {
            $('#ticker li:first').slideUp(function () {          $(this).appendTo($('#ticker')).slideDown(); });
        }

        setInterval(function () { tick() }, 5000);



    //window.setInterval(AlertCheckFunction, 5000);

    //function AlertCheckFunction() { alert('test'); }

        //window.setInterval(function () {
        //    $('AlertCheckFunction');
        //}, 2000);


 //    function alert() {
 //        $('AlertCheckFunction')
 //    }

 //    setInterval(function () { alert() }, 60000)

 //window.setInterval(function() {

 //$.get('AlertCheckFunction', function(result) {

 //});
 //}, 3000);
 </script>

HOME CONTROLLER

      public ActionResult AlertCheckFunction()
    {
        List<String> Messages = new List<String>();


        foreach (var i in db.Ingredients)
        {

            if (i.Quantity < i.ReOrderPoint)
            {
                Messages.Add("The quantity of " + i.IngredientName + "Is less than the ReOrderPoint, Suggest placing another order for this ingredient!");

            }
            else
            {
                Messages.Add("No alerts from Ingredeints");
            }

        }




        foreach (var c in db.Customers)
        {
            if (DateTime.Now == c.Birthday)
            {
                Messages.Add("It is " + c.Name + "'s" + "Birthday Today!");
            }
            else
            {
                Messages.Add("No alerts from Customer!");
            }
        }




        foreach (var i in db.Inventories)
        {
            if (i.InvQuantity <= 5)
            {
                Messages.Add("The Inventory of " + i.Name + "Is less than or equal to 5, Consider making new batch");
            }
            else
            {
                Messages.Add("No alerts from Inventories");
            }
        }



        //DateTime lastMonth = DateTime.Now.AddMonths(-1);
        //DateTime twoMonthsAgo = DateTime.Now.AddMonths(-2);

        //var sales = db.Sales.Where(j => j.SaleId).ToList();

        // foreach (var x in db.Sales)
        // {
        //     var alerts = db.Sales.Where(x => x.SaleId.Count);

        ViewBag.Message = Messages;

        return RedirectToAction("Index", "Home");
    }






   HTML 



     <div>
                    <ul id="ticker">
                        @if (ViewBag.Messages != null)
                        {
                            foreach (var v in ViewBag.Message)
                            {
                                <li>
                                    @v
                                </li>
                            }
                        }
                    </ul>
     </div>
  • The public Actionresult is the start of my code on my home controller and the div at the bottom is where i call it in the html. Any help and easiest and most mundane solution would be appreciated, its 1:30 on finals week and my critical thinking skills are about shot right now so its hard to comprehend anything right now ha – Josh Walker Dec 03 '15 at 07:32
  • Please format your code properly. – RN Kushwaha Dec 26 '15 at 09:52

2 Answers2

0

I think you are mixing up a bunch of Javascript and MVC code. You cannot call the method AlertCheckFunction from Javascript if it is located in your HomeController.

What you can do is, ensure that the method is available as a Controller Action and accessible on a URL like /Home/AlertCheckFunction.

Your attempt to a $.get is the closest to the answer. Check if the function and its response (preferably in JSON) is available at a URL and make the call in the following pattern.

setInterval(function () {
    $.get('/Home/AlertCheckFunction', function (resp) {
        console.log(resp); // This will be the JSON response.
    });
}, 3000);

You might also want to pass any parameters that you want to check in that function. Parameters can be passed as a query string. More info here Use querystring variables in MVC controller

Community
  • 1
  • 1
Omkar Khair
  • 1,364
  • 2
  • 17
  • 40
  • Thank you for this, it helped a bit but I am not really familiar with ajax or Json and I am not really sure where to go from here-i posted more of my code if it helps – Josh Walker Dec 03 '15 at 08:05
  • See the answer above. Change your function's return type to JsonResult (though it works with ActionResult too but it's clearer this way). Once you constructed your lists just put them in a JSON string like this: return Json(new {Messages = messages}); – RekaB Dec 04 '15 at 07:20
0

Instead of putting your items to the ViewBag in the controller, try returning a JSON string with the messages you want to put in your alert box. Then your ticker can do an ajax call to your controller and get the new alerts.

Alternatively you can look into something like angular, knockout or ember that will change your DOM for you when the data behind changes - if you structure it right.

In your controller:

public JsonResult GetAlerts()
{
    return Json(Alerts, JsonRequestBehavior.AllowGet);
}

And in your view:

$.ajax({
   url: '@Url.Action("GetAlerts")',
   // data: {'alertType': 1}, if you wanted to send some data. The parameter name will have to be _exactly_ the same
   type: 'GET',
   success: function (response) {
       $("#alertsDiv").html(response);
}
});
RekaB
  • 438
  • 5
  • 14