Apr
25
Written by:
Michael Washington
4/25/2013 7:25 PM
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

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

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

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

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.

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

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.

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

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

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

You may have a need to programmatically disable a button.

In the screen designer we add a button.

We name the button DisabledButton.

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

Sometimes we desire to show a message box…

… and respond to user input.

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


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.

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.

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

Next we add the query to the screen.

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

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.

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

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

You may need to get the location of the user.

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.

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

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

In the screen designer we add a Custom Control.

Use the default value of Screen for the data binding.

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

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

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.

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)
10 comment(s) so far...
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
|
@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
|
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
|
@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
|
how to implement this scenario with kendo combobox instead popups?
By mokey on
5/4/2013 9:06 PM
|
@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
|
Hello,
* How to get the selected item value of a combo box "Account No" in a LightSwitch Desktop application screen. * Also i want to update the other controls based on the selected value in combo box. * Based on the Account no selected; I have to update other control's combo boxes show the respective Address, City and State of the Account
By J A Joseph on
2/20/2015 1:18 PM
|
@J A Joseph - Please post on the Microsoft LightSwitch Forums - http://social.msdn.microsoft.com/Forums/en-US/lightswitch/threads
By Michael Washington on
2/20/2015 1:18 PM
|
Michael, I'm trying to perform HTML client validation in the "beforeApplyChanges" method as you show here, but the errors only show up if I click the 'Save' button twice. The code fires on the first click, but the errors only appear after the second click. Please help. Here's my code:
myapp.AddEditCapIQFacultyStaff.beforeApplyChanges = function (screen) { var result = true;
if (screen.tb_FacultyStaff.NetID == undefined) { screen.findContentItem("NetID").validationResults = [ new msls.ValidationResult( screen.tb_FacultyStaff.details.properties.NetID, "NetID is required.") ]; result = false; }
if (screen.tb_FacultyStaff.Email == undefined) { screen.findContentItem("Email").validationResults = [ new msls.ValidationResult( screen.tb_FacultyStaff.details.properties.Email, "Email is required.") ]; result = false; }
return result; };
By Mike on
3/10/2015 8:05 AM
|
@Mike - Please post on the Microsoft LightSwitch Forums - http://social.msdn.microsoft.com/Forums/en-US/lightswitch/threads
By Michael Washington on
3/10/2015 8:05 AM
|