You are here:   Blog
Register   |  Login

LightSwitch News

 

Apr 25

Written by: Michael Washington
4/25/2013 7:25 PM  RssIcon

clip_image002

The Microsoft Visual Studio LightSwitch Team recently posted example JavaScript code to accompany the MSDN documentation: How to: Modify an HTML Screen by Using Code. In this article, we will look at some of the examples they posted and provide a step-by-step walk-thru.

Set a Default Value On a Data Entry Screen

clip_image003

When you have a screen where the user creates a new record, you will usually want to set default values.

clip_image004

However, without custom JavaScript, default values will not be set.

clip_image005

To set the default values, we open the entity that we want to set the values for, and select the HTMLClient tab, and then the created method.

We use the following code:

myapp.Order.created = function (entity) {
    entity.OrderDate = new Date();
    entity.OrderStatus = 'New';
};

Format a Number

clip_image006

LightSwitch contains many controls to format values such as dates and currencies. However, sometimes you have special formats that you require such as a number that needs to show two digits after the decimal.

clip_image007

To implement our custom formatting, we open the page in the screen designer, select the control, and select Edit PostRender Code.

We use the following code:

myapp.AddEditProduct.ProductWeight_postRender = function (element, contentItem) {
    contentItem.dataBind("value", function (value) {
        if (value) {
            $(element).text(value.toFixed(2));
        }
    });
};

Validate Data On A Screen

clip_image008

LightSwitch automatically provides validation for most situations. For example, if you have an integer field and the user enters string characters, LightSwitch will automatically show validation errors when the user attempts to save.

However, sometimes you require custom validation.

clip_image009

To implement our custom validation, we open the page in the screen designer, and select beforeApplyChanges.

We use the following code:

myapp.AddEditCustomer.beforeApplyChanges = function (screen) {
    if (screen.Customer.ContactName.indexOf('!') != -1) {
        screen.findContentItem("ContactName").validationResults = [
        new msls.ValidationResult(
        screen.Customer.details.properties.ContactName,
        "Contact Name cannot contain the character '!'.")
        ];
        return false;
    }
};

Set the Screen Title Dynamically

clip_image010

JavaScript is required to programmatically set the title of a screen.

clip_image011

We open the screen in the screen designer, and select the created method.

We use the following code for the method:

myapp.AddEditCustomer.created = function (screen) {
    // Set the screen title dynamically
    var name;
    name = screen.Customer.ContactName;
    screen.details.displayName = "Info: " + name;
};

Disable a Button

clip_image012

You may have a need to programmatically disable a button.

clip_image013

In the screen designer we add a button.

clip_image014

We name the button DisabledButton.

clip_image015

We select the created method for the screen.

We use the following code for the method:

myapp.BrowseCustomers.created = function (screen) {
    // Find DisabledButton and disable it
    screen.findContentItem("DisabledButton").isEnabled = false;
};

Show a Message Box, And Respond To a User Selection

clip_image016

Sometimes we desire to show a message box…

clip_image017

… and respond to user input.

clip_image018

To implement the message box, we add a button to the screen in the screen designer.

We right-click on the method for the button and use the following code:

myapp.BrowseCustomers.EnabledButton_execute = function (screen) {
    msls.showMessageBox("Please choose the appropriate button", {
        title: "This is a message box",
        buttons: msls.MessageBoxButtons.yesNoCancel
    })
        .then(function (result) {
        if (result === msls.MessageBoxResult.yes) {
            alert("Yes button was chosen");
        }
        else if (result === msls.MessageBoxResult.no) {
            alert("No button was chosen");
        }
        else if (result === msls.MessageBoxResult.cancel) {
            alert("Please choose either Yes or No");
        }
    });
};

Create A Custom Modal Picker By Using A Popup

clip_image019

clip_image020

LightSwitch will automatically create popups that allow you to choose a value from a collection. However, you may have a situation where you want to control the choices in the popup.

clip_image021

In our sample, we have set a Product to not be active.

We do not want it to show as an option in the popup.

clip_image022

We create a query of only Active Products using the following query:

clip_image023

Next we add the query to the screen.

clip_image024

In the screen designer, we select Add Data Item, Query, and ActiveProducts.

clip_image025

We click on the Popups node in the screen designer and select Add Popup.

We add the ActiveProducts collection to a popup by dragging and dropping it on the popup.

clip_image026

We create a button and set it to open the popup.

clip_image027

We select the created method for the screen and use the following code for the method:

myapp.AddEditOrderDetail.created = function (screen) {
    screen.findContentItem("ActiveProducts")
        .dataBind("value.selectedItem", function (newValue) {
        if (newValue !== undefined && newValue !== null) {
            //Whenever selectedItem for Products changes, 
            // update the Product value on the main page 
            screen.OrderDetail.setProduct(newValue);
            //Close popup, if one is open. 
            screen.closePopup();
        }
    });
};

Get The Location Of A Device

clip_image028

You may need to get the location of the user.

clip_image029

We first add two string properties to the screen (using the Add Data Item button).

We then drag the properties on to the screen designer.

clip_image030

We then select the created method for the screen and use the following code to set the values:

myapp.Main.created = function (screen) {
    // Set latitude and longitude
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (pos) {
            screen.latitude = pos.coords.latitude.toString();
            screen.longitude = pos.coords.longitude.toString();
        });
    }
    else {
        alert("Geolocation not supported");
    }
};

Render HTML Directly On a Screen

clip_image031

You can render HTML markup directly on the screen. In this example we will use the HTML marquee tag to display a scrolling message.

clip_image032

In the screen designer we add a Custom Control.

clip_image033

Use the default value of Screen for the data binding.

clip_image034

In the Properties for the control, we select Edit Render Code and use the following code:

myapp.Main.ScreenContent_render = function (element, contentItem) {
    //Get the name of the page
    var pageName = contentItem.screen.details.displayName;
    element.innerHTML = '<marquee>The name of this page is ' + pageName + '</marquee>';
};

Use A JQuery Mobile Control

clip_image035

There are several JQuery controls that we can implement. In this example we will implement the JQuery slider.

clip_image036

We add a SliderValue integer property to the screen and drag it to the screen designer and change the control to a Custom Control.

We could also bind to a normal table value.

clip_image037

In the Properties for the control, we select Edit Render Code and use the following code:

myapp.Main.SliderValue_render = function (element, contentItem) {
    createSlider(element, contentItem, 0, 100);
};
function createSlider(element, contentItem, min, max) {
    // Generate the input element.
    $(element).append('<input type="range" min="' + min +
        '" max="' + max + '" value="' + contentItem.value + '" />');
};

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have Visual Studio 2012 Update 2 installed to run the code)

6 comment(s) so far...


Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

Michael, thanks for provided a walk-through of some of the most common LS HTML Client scenarios. You are going to save a lot of time for people just learning LightSwitch for the first time and wondoering how to do some of these simple common tasks.

On another note, do you know how to create a list item that has both a picture and text? There is a Leading Lightswitch article in the Aptil 2013 issue of MSDN Magazine (http://msdn.microsoft.com/en-us/magazine/dn133441.aspx) that show a basic example of creating a LightSwitch application. At then end of the application there is a picture of 3 screen shots of the app after the unpublished "Final Touches" that shows the a Tile List that contains a picture of the animal along with the Name in text format. Do you now how to produce that?

By Christopher DeMars on   4/26/2013 10:15 AM
Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

@Christopher DeMars - When you make a list item you can put anything in the list. You can make a group and show a picture next to text. The only thing is you need to have all the items in the same collection. If they are not use a WCF RIA Service to combine data from multiple collections. For more help post to the official LightSwitch Forum: http://social.msdn.microsoft.com/Forums/en-US/lightswitch/threads

By Michael Washington on   4/26/2013 10:18 AM
Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

Really nice examples.
But when talking about default values, one common scenario is missing: Having a modal picker bound to a table.

By Marco on   5/2/2013 5:34 AM
Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

@Marco - The "Create A Custom Modal Picker By Using A Popup" example is bound to a table.

By Michael Washington on   5/2/2013 5:35 AM
Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

how to implement this scenario with kendo combobox instead popups?

By mokey on   5/4/2013 9:06 PM
Gravatar

Re: Walk-thru Examples of Common Visual Studio LightSwitch JavaScript

@mokey - Please post on the Microsoft LightSwitch Forums - http://social.msdn.microsoft.com/Forums/en-US/lightswitch/threads

By Michael Washington on   5/5/2013 4:25 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation