Showing posts with label HTML 5. Show all posts
Showing posts with label HTML 5. Show all posts

Friday, January 8, 2016

How to share Localization Resource in ASP.Net 5 MVC with Javascript

ASP.Net MVC projects can use Resource files to do localization. Its very easy to use those resource files in razor view files. For each resource, there are multiple resource files referring to different languages. ASP.Net treats those resource files as one resource class. The application will use specific language resource during the run time while one language is selected.

Regarding the Javascript, if we want to apply those resource files, we need to send them to Javascript one by one in razor file. To avoid those tedious process and to improve the independence of Javascript, we can create resource section in razor file using HTML 5 section tag. And let Javascript to read those resource by themselves. Here is the code in view:
<section class="myResouceLabels"
    data-Message1 = "@MyResources.MyMessage1"
    data-Message2 = "@MyResources.MyMessage2">
</section>
In your Javascript:
    // Return a message contained in the container
    function GetResourceMessage(msgId) {
        var container = $(".myResouceLabels");
        if (container.length == 0) return;
        return container.attr(msgId);
    }
    ....
    alert(GetResourceMessage(data-Message1);
    alert(GetResourceMessage(data-Message1);
Note section tag contained all attributes with data as leading string, which is different than other tags. Be careful not to make mistake!!!

Definitely, you need css decorating to let the section don't be displayed.
myResouceLabels { display: none }

Wednesday, December 2, 2015

Applying jQuery DataTable 1.10+ with ASP.Net MVC 5 Tutorial

jQuery DataTable is a jQuery plugin to show table of data.
Note jQuery DataTable had used old-style attribute names like "bProcessing" instead of new name "processing" for older version. Thus Google DataTable will get lots of results based on the old naming style.

Creating DataTable with Customized Columns

The Model part:

The Html part:
<table id="example">
    <thead>
      <tr><th>Sites</th></tr>
    </thead>
    <tbody>
      <tr><td>SitePoint</td></tr>
      <tr><td>Learnable</td></tr>
      <tr><td>Flippa</td></tr>
    </tbody>
</table>
The javascript part:
<script type="text/javascript" charset="utf-8">
    var myTable;
    $(document).ready(function() {
        myTable = $('#jobs-table').dataTable( {
            "destroy": true,
            "processing": true,
            "serverSide": true,
            "ordering": false,
            "info": true,
            "paging": false,
            "searching": false,
            "scrollX": true,
            "ajax": {
                "url": "/DataController/GetDataForTable",
                "type": "GET",
                "data": { "date": startDate}
            },
            "columnDefs": [ {
                "targets": 0, /*column index counting from the left*/
                "searchable": false,
                "className": "dt-right", /* Right align text in the header and body */
                "render": function ( data, type, row ) {
                    return data +' ('+ row[3]+')';
                },
                { "visible": false,  "targets": [ 3 ] }
            }],
            "columns": [
                { "data": "StartDate" },
                { "data": "Players" },
                { "data": "TotalSession" },
            ]
        })
    });
</script>
Note the above javascript will set the data table to align right which defined in the columnDefs for the 1st column.

In addition, the first column will also display the 4th column combined through render function. And it hides the 4th column. The render function has 3 parameters, data, type, and row. The data refers the data for the cell, and also the type.

Serverside DataTable

Note above dataTable define contains serverSide as true, which means the data source will come from server side.  Actually, above code contains ajax parameter, which refers a MVC controller method named GetDataForTable, which returned json data to loading the data table.

    public class DataController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        
        public JsonResult GetDataForTable(string startDate)
        {
            try
            {
                if (startDate == null)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    MyDataModel model = (new MyDataModelService()).GetMyDataModel(startDate);
                    return Json(new {
                        draw = 1, 
                        recordsTotal = model.MyDataList.Count,
                        recordsFiltered = model.MyDataList.Count,
                        data = model.MyDataList }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
    }
Note the json data contained draw, recordsTotal, recordsFiltered, and data, which are needed for data table.

Reference:
http://www.codeproject.com/Tips/844403/jQuery-Datatables-For-Beginners
https://datatables.net/manual/styling/classes
https://datatables.net/manual/server-side
http://legacy.datatables.net/usage/columns
http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
http://stackoverflow.com/questions/22737957/use-jquery-datatables-server-side-processing-with-mvc-serialize-criteria-form-a/22742742#22742742
https://www.echosteg.com/jquery-datatables-asp.net-mvc5-server-side

Tuesday, December 1, 2015

Apple Style JQuery Toggle Button

JQuery Toggle Button is an Apple style toggle button which has following very nice look and feel.
The light theme is very nice looking. To apply it in your web page, add following css  at first:
  <head>
    <title>My cool page</title>

    <link rel="stylesheet" href="css/toggles.css">
    <link rel="stylesheet" href="css/toggles-light.css">

    <!-- ALL OF THE THEMES -->
    <!-- <link rel="stylesheet" href="css/toggles-all.css"> -->

    <!-- ALL OF THE CSS AND THEMES IN ONE FILE -->
    <!-- <link rel="stylesheet" href="css/toggles-full.css"> -->
and javascript file at latter.
    <script src="js/toggles.js" type="text/javascript"></script>
    <!-- MINIFIED JS - recommended for production -->
    <!-- <script src="js/toggles.min,js" type="text/javascript"></script> -->
  </body>
</html>
Add following to your web page to place the toggle.
<div class="toggle toggle-light">
Add following javascript  to your web page javascript file.
// Simplest way:
$('.toggle').toggles();
// With options (defaults shown below)
$('.toggle').toggles({
  drag: true, // allow dragging the toggle between positions
  click: true, // allow clicking on the toggle
  text: {
    on: 'ON', // text for the ON position
    off: 'OFF' // and off
  },
  on: true, // is the toggle ON on init
  animate: 250, // animation time (ms)
  easing: 'swing', // animation transition easing function
  checkbox: null, // the checkbox to toggle (for use in forms)
  clicker: null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
  width: 50, // width used if not set in css
  height: 20, // height if not set in css
  type: 'compact' // if this is set to 'select' then the select style toggle will be used
});


// Getting notified of changes, and the new state:
$('.toggle').on('toggle', function(e, active) {
  if (active) {
    console.log('Toggle is now ON!');
  } else {
    console.log('Toggle is now OFF!');
  }
});

Following Javascript code can be used to change toggle states:
// initiate a new Toggles class
$('.toggles').toggles({
  on: true
});

// the underlying Toggles class can be accessed
var myToggle = $('.toggles').data('toggles');

console.log(myToggle.active); // true
myToggle.toggle();
console.log(myToggle.active); // false

// set the state to 'false'
// will not do anything if the state is already false
myToggle.toggle(false);
console.log(myToggle.active); // false

// passing a boolean in place of options on an active toggle element
// will set the state
$('.toggles').toggles(true);
console.log(myToggle.active); // true

// the toggle-active data attribute stores the state too
console.log($('.toggles').data('toggle-active')); // true

// myToggle.toggle(state, noAnimate, noEvent)

// don't animate the change
myToggle.toggle(false, true);

// change the state without triggering an event 
myToggle.toggle(true, false, true);
Following javascript can be used to disable and enable your toggle control:
// your toggle element
var toggle = $('.toggle');

// initialise it
toggle.toggles();

// disable the toggle element (click + drag will no longer work)
toggle.toggleClass('disabled', true);

// setting the state via JS is NOT disabled, only user input
// toggle the toggle on
toggle.toggles(true);

// re-enable the toggle
toggle.toggleClass('disabled', false);
My own example:
Html part:
<div id="buttonAutoRefresh" class="toggle toggle-light"></div>
Javascript part:
    var autoRefresh;
    var SetAutoRefreshOnOff = function () {
        var button = $('#buttonAutoRefresh');
        var toggle = button.data('toggles');
        //alert(toggle.active);
        //button.Toggle(); //switch the states of the button
        if (toggle.active) {
            autoRefresh = setInterval(LoadPageContent, 15000); //only set one time
        }
        else if (typeof (autoRefresh) != "undefined") {
            clearInterval(autoRefresh); //clear autoRefresh
        }
    }

    // initiate a new Toggles class
    $('.toggle').toggles({ width: 50 });
    $('.toggle').on('toggle', SetAutoRefreshOnOff);
Reference:
https://github.com/simontabor/jquery-toggles
http://simontabor.com/labs/toggles/