Category Archives: Jquery

Charger des scripts dans une vue partielle

Standard

En ASP.NET MVC,  il arrive que l’on veuille écrire ou référencer des scripts depuis une vue partielle, afin de déléguer l’entière responsabilité de certains scripts et de leur fonctionnement à ce bout de vue uniquement. Par exemple, une vue partielle destinée à de la conversation instantanée, à du « chat », présentera tous les éléments UI nécessaires à l’envoi et à la réception de messages instantanés si la personne est authentifiée et s’occupera également de s’assurer que les bons scripts, tels que SignalR par exemple, ont été chargés et exécutés en vue du bon fonctionnement du chat.

Ces scripts nécessitent souvent que d’autres scripts aient été chargés au préalable, comme JQuery par exemple. Malheureusement, une vue partielle se situe souvent en milieu de document et les scripts de base, eux, souvent juste avant la balise de fermeture du body, afin de ne pas bloquer le rendu de la page et de conserver de bonnes performances. Sachant qu’ils se chargent et s’exécutent dans l’ordre de leur référencement, les scripts situés dans la vue partielle ne fonctionneront pas car les dépendances n’auront pas encore été chargées.

Ce problème se résout facilement dans une vue basique car il est possible de redéfinir une section en ASP.NET MVC : le développeur peut redéfinir la section « Scripts » qui se situerait après les scripts de base de fin de body. Mais dans une vue partielle, il est impossible de redéfinir une section. Ainsi, un script présent dans une vue partielle nécessitant JQuery risque de planter en disant que $ est « undefined ».

Read the rest of this entry

How to display little temporary javascript messages to the user ?

Standard

Hello everyone,

Today, I’ll talk about displaying little notification messages at the bottom of a web page, and how to make them appear and vanish after a few seconds in a customizable way, thanks to JQuery. Let’s say we need to display messages that would stack up against each other, and each would appear and disappear after a specified time. We want to :

–          Style the notifications (error, validation…)
–          Style the whole notification template and put whatever we want in it
–          Notifications should anchor to the bottom of the page, wherever we’re scrolling at.
–          All this within a jquery plugin ?

To ease our task, we’d rather use jquery template.

First, refer the scripts you need at the end of the page to prevent them from slowing html rendering :

  <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/jquery-tmpl.js"></script>
    <script src="Scripts/notificationMaker.js"></script> <!--our plugin-->

Then create your page. For the sake of the demo, we add 3 buttons, one for displaying negative messages, one for good messages, the last one for custom templated messages. We add a long text excerpt to check that scrolling doesn’t affect our notification messages anchor.

 <div id="whole">
            <div id="buttons">
                <textarea id="myMessage"></textarea>
                <br />
                <button id="notification-negative">post alert</button>
                <button id="notification-positive">post good message</button>
                <br />

                <button id="templated-notification">post custom message</button>
            </div>
            <div id="content">
                    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
            1914 translation by H. Rackham

             "... and so on ... (big text to show even when scrolling notification messages stay put"
            </div>
        </div>

Then write the script that will use our notification jquery plugin. I just wrote an example, but you can use it any way you want. First function will use a simple css class for styling good messages. Second function will use a different css class for errors then specify how many milliseconds the message will appear.

<script type="text/javascript">
        $(document).ready(function () {
            $("#notification-positive").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-message",
                    })
                ;
            });
            $("#notification-negative").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-error",
                        time:4000,
                    })
                ;
            });
       });
    </script>

A third function specify a custom template, giving its selector.

$("#templated-notification").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        template: "#my-message-template",
                    });
            });

And here’s the template

 <script id="my-message-template" type="text/html">
        <div class="templated-part">
            <p>{{= Message }}</p>
        </div>
    </script>

Of course you could build the template the way you want, with pictures, other div, span or whatever inside it. Just evaluate the “Message” variable wherever you want to show the text message.

Now let’s show the interesting part, the plugin part  with all comments :

(function ($) {
    var notificationMaker = {
        messageArea: null,
        init: function () { //just once at the beginning to insert the message area once into the DOM
            if (notificationMaker.messageArea)
                return;
            messageArea = document.createElement('div');
            $(messageArea).addClass("notification-area"); //style the notification area in stylesheet if you don't want it that way
            $("body").append(messageArea);
        },
        //method that shows the messages for a specific time and with animations
        showMessage: function (elm, time) {
            $(elm).slideToggle();//or use whatever animation you want
            setTimeout(function () {
                $(elm).slideToggle({
                    complete: function () {
                        messageArea.removeChild(elm); //important, remove the element from DOM so that DOM doesn't grow too much
                    }
                });
            }, time);
        },
        methods: {
            //options : cssClass, custom template, time to display the message
            postMessage: function (message, options) {
                var element = null;
                options = (!options) ? {} : options;
                var time = (options.time) ? options.time : 3000; //sets a default time if none specified
                if (!options.template) { //if no template, that's gonna be a paragraph
                    element = document.createElement('p');
                    if (options.cssClass) //if there's a specified css class
                        $(element).addClass(options.cssClass);
                    $(element).text(message); //sets the text
                }
                else {
                    element = $(options.template).tmpl({ Message: message })[0]; //apply a jquery template,
                    //take the first of the array a jquery template will return an array
                    //we need an object only to remove it from DOM later
                }
                $(element).hide();
                $(messageArea).append(element);
                notificationMaker.showMessage(element, time);
                return this;
            },
        }
    };

    //add the plugin method to jquery methods, beware not to replace any jquery native methods.
    $.postMessage = function(method) {
        var methods = notificationMaker.methods;
        if (typeof method === 'string') {
            if (method !== "")
                return methods.postMessage.apply(this, arguments);
            else return this;
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.notificationMaker');
        }
    };
    notificationMaker.init();

})(jQuery);

That way, it is clipped to the page’s bottom, no matter if you scroll the page, thanks to a custom JQuery plugin.

Here’s the zipped project if you want the whole thing with css :

Client side notifications sample

Enjoy 😉

Kendo autocomplete box and server filtering

Standard

Hello all,
A very simple thought today but as it took me some time to figure it out, I thought that little post could make you spare some.

I used the autocomplete box from kendo UI bound with a remote datasource. Based on the user input, server returned a set of matching words, processing quotes for example for a google-like exact search. But the autocomplete box kept filtering client-side too, looking for quotes in the results set and filtering all my server results…. I finally figured out that setting “serverFiltering = true” on the datasource itself stopped the client-side filtering !
Happy coding !

var dataSource = new kendo.data.DataSource({
      transport: {
         read: { url : "http....",
        },
      success: function (response) {
         o.success(response);
       }
 },
 serverFiltering: true, //set it to true to stop client-side filtering
 total: 5, //five results only
 optionLabel: "Type in a...",
 });

myAutoComplete.kendoAutoComplete({
 dataSource: dataSource,
 dataTextField: "toto",
 dataValueField: "titi",
 …
 )} ;

Calling a server method (asp.net) from the browser

Standard

Sometimes,  you use JQuery within your Asp.Net projects to provide richer and more interactive web experience. The user now can drag and drop, admire your smooth animations, interact in many ways with the page and experience a whole bunch of other funny things. On top of that, you could appreciate how integrating JQuery with ASP.NET projects is pretty straightforward.

Moreover, to get your page to work properly, you sometimes have to  focus on client-sided effects only and to forget about… postbacks ! Your HTML elements then won’t be bound to the server and won’t trigger any postbacks nor be referenced in any aspx class. They will have nothing to do with the viewstate and they won’t notify any data change.  As a consequence, if the user changes the webpage content, some properties or the order of a few elements  through JQuery manipulations, the server won’t be able to retrieve by itself those changes. Let’s stick with our previous example : the dynamic forms (dynamic webforms with JQuery). The user wants to create his own forms. It was all implemented through Javascript and JQuery, adding, dragging, dropping.

>> Could we now save it all to our database thanks to a little Asp.Net method ? which means formatting the data, sending it to the server which will eventually treat it. So how to send back data to  the server ?
>>How to call a server method without the postback mechanism but just with pure raw HTML controls never bound to the server ?
Of course, a simple Ajax call will do the trick !
We’ll see how  to :

  1. build this simple Ajax call to the asp.net server
  2. how to format basic data with JSON
  3. how to format more complex data like serializing and deserializing Javascript-.NET object, even with inheritance. Read the rest of this entry

Dynamic web forms with jquery

Standard

Let’s say you want to enable the user to create his own forms with the fields and the questions of his choice. The user should just choose the fields  from a list  and those fields should be sortable, draggable, deletable so that he can move them, change their order by simply dragging and dropping objects.
Well, see google documents, add new form, something like this, no ? well I can show you the basics with jquery to build dynamic forms.

To sum up, we want a sortable dynamic list of fields. First of all, you need to inject html in the webpage areas you define. Then we will enable sorting and dropping and throwing away.

First, here’s the list from which the user chooses the fields :

<select id="fieldtoadd" style="float:left">
<option value="">add new field...</option>
<option value="text">text</option>
<option value="textarea">multiple line text</option>
<option value="radiobutton">multiple choice</option>
<option value="checkbox">checkbox</option>
<option value="uploadfile">upload a file</option>
</select>

here’s the <div> element where to inject the fields :


<div id="fieldslist" style="float:left"></div>

Read the rest of this entry