Tuesday, September 12, 2017

MVC Razor Dates

How many ways can we format a date...

 
If it is already a Date or DateTime type

            @item.ContributedDate.ToShortDateString()

       
    If is is a Nullable Date or DateTime type
  
                @if (item.ExpirationDate != null)
                {
                    @item.ExpirationDate.Value.ToString("d")
                }

Nullable Date Fields in Razor

    @if(Model.ExpirationDate.HasValue) {
              Model.ExpirationDate.Value.ToShortDateString();
       
            }

Awesome Tooltips

The CSS

.tooltip-no-link{  cursor: default;color:#ffffff;}

.tooltip-inner {
  max-width: 400px;
  padding: 3px 8px;
  color: #000;
  text-align: left;
  background-color: antiquewhite;
  border:#000 1px solid;
  border-radius: 4px;
  cursor:pointer;
}
.tooltip {
    display: block;
    cursor: pointer;
    /*box-shadow: rgba(0, 0, 0, 0.3) 0 2px 10px;*/
}
.tooltip.bottom {
  padding: 0;
  margin-top: 3px;
}

The Jquery

<script>
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});
</script>

The HTML


  <a class="tooltip-no-link" data-html="true" data-toggle="tooltip" data-placement="right" title="@db.DbConnection">@db.DbName</a>

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);
        }

Client Validation

$(function () {
    $("#yourSubmitButtonID").click(function (e) {
        e.preventDefault();
        var _this = $(this);
        var _form = _this.closest("form");

        var validator = $("form").validate(); // obtain validator
        var anyError = false;
        _form.find("input").each(function () {
            if (!validator.element(this)) { // validate every input element inside this step
                anyError = true;
            }
        });

        if (anyError)
            return false; // exit if any error found    

        $.post(_form.attr("action"), _form.serialize(), function (data) {
             //check the result and do whatever you want
        })
    });

});

Distinct Items

Each item that is duplicated
List<String> duplicates = lst.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

A list of all duplicates
var duplicates = lst.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

Another Way
  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };
    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }
 var arrString = "Hello Ronda, I'm calling you Ronda. How are you Ronda.".Split(" ".ToCharArray());
        
 var duplicates = from wordCollection in arrString
                  group wordCollection by wordCollection   into g
                  where g.Count() > 1
                  select new { g.Key, Count = g.Count() } ;  

Jquery Use Returned Value of Json object

 $('#SubmitAttribute').click(function () {
        var productid = $('#ProductId :selected').val();

        var source = {
            'ProductId': $('#ProductId :selected').val(),
            'ProductAttributeId': $('#ProductAttributeId :selected').val(),

        }
        $.ajax({
            type: "POST",
            datatype: 'jsonp',
            data: source,
            url: "/api/ProductAttributeMapping/",
            success: function (results) {
                resultvalue = results;

            }

        }).done(function (data, status, jqXHR) {
            $('#attributelist').html("");

            $.getJSON('/ProductAttributes/GetAttributes/' + resultvalue.ProductId, function (data) {


                $.each(data, function (index, items) {
                    $("#attributelist").append(items.Text + '<br />');
                });
            })
        });
    });