RaviKant Hudda RaviKant Hudda - 4 months ago 15
ASP.NET (C#) Question

How to populate data repeatedly from list returned by action in mvc4?

I am a kind of newbie and I am having problem in reading data that I want to get from database and want to show in a span. My problem is this that I have brought data in controller but now I want to show that data in view. I am able to access specific data from list but I want to show data in repeat mode as like news.
My controller part is given here

public ActionResult Index()
{
List<Quote> quote = dbContext.quotes.ToList();
return View(quote);
}


View part is

<blockquote>
@foreach
(var items in @Model)
{
@items.quote
}
</blockquote>


what logic should I implement here to fetch data in repeat mode so that I can every quote on hourly basis.

Answer

You could use location.reload(); in javascript which will re-load your page every hour and fetch the latest news:

@model IEnumerable<MVCTutorial.Models.Quote>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Quotes</title>
    <script type="text/javascript">
        setInterval(function ()
        {
            location.reload();

        }, 3600000);//3600000 milliseconds = 1 hour
    </script>
</head>
<body>
    <blockquote>
        @foreach(var item in Model)
        {
            <span>@String.Format("{0}-{1}",item.ID,item.QuoteName)</span><br />
        }
    </blockquote>
</body>
</html>

EDIT

To get only the latest items periodically you could make an AJAX call using $.getJSON and append the latest items to the list.

Controller action method:

public JsonResult GetLatestNews()
{
    //Write the query here to get the latest items...
    List<Quote> quotes = dbContext.quotes.ToList();
    return Json(quotes, JsonRequestBehavior.AllowGet);
}

View:

@model IEnumerable<MVCTutorial.Models.Quote>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Quotes</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            setInterval(function () {
                $.getJSON("@Url.Action("GetLatestNews","Quote")", function (data) {

                    for(var i = 0;i < data.length;i++){
                        var id = data[i].ID;
                        var quoteName = data[i].QuoteName;

                        var quote = "<span>" + id + "-" + quoteName + "</span><br />";
                        $("#quotes").append(quote);
                    }
                });

            }, 3600000);//3600000 milliseconds = 1 hour
        });
    </script>

</head>
<body>
    <blockquote id="quotes">
        @foreach (var item in @Model)
        {
            <span>@String.Format("{0}-{1}", item.ID, item.QuoteName)</span><br />
        }
    </blockquote>
</body>
</html>