Json News in a Partial View

News on the front page is always nice
Quick way to drop your news into a Partial view so that you can use it anywhere

Create your Partial View Just make it empty


Add a Div for your News

<div id="news"></div>

Add script  which loads the news - sidenote - I a have learned that you can not use .append lines when adding conditional data because it inherently closes your tag for you.  So I am using an array instead and then appending to the news div at the very end.


<script type="text/javascript">
    $(document).ready(function() {
     
            $('#news').html("");
            $('#L1').removeClass("hidden");
            var ROOT = '@Url.Content("~/")';
            if (ROOT == '/') { ROOT = '' };
            $.getJSON(ROOT + '/home/SiteNews/', function (data) {
                   if (data != null) {
                    $('#news').html('<h3>CURRENT NEWS</h3><hr />');
                }
                $.each(data, function (i, news) {
                    var array = [];//
                    var m = moment();
                    array.push("<b>" + Date(data[i].ContributedDate) + "</b><br /><hr />" + data[i].ArticleText + "<br />");
                  if (data[i].ArticleUrl != null) {
                      array.push("<a href=" + data[i].ArticleUrl + " target=_new>More Info...</a>");
                  }
                  $('#news').append("<div class='col-sm-3 newsbox'>" + array.join('') + "</div>");
                    //Posted By:  " + data[i].ContributedBy + "
                });
           
            })
        })
</script>

I am returning my news from a JsonResult like this:

 public JsonResult SiteNews()
        {
            var programs = (from s in db.SiteNews
                            where s.featured==true
                            select s);

            return Json(programs, JsonRequestBehavior.AllowGet);
        }

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax