M# Tutorials

Learn to build .NET applications with M#. Our step-by-step tutorials will get you up-to-speed rapidly.
If you already know ASP.NET and C#, you can master M# in a week or two.

Display elements

Displaying the details of an instance is a frequent operation in an application, M# allows you to easily create and implement a page containing all the information of an object.
By using the M# view generation you will be able to sync your model with its view, which means if you delete a property from your model it will also be deleted from your view.
In this lesson we will learn how to generate a view and how it works.

Creation of a View Module

You learnt in Chapter 6 how to create a module.
In M# a View is a module, so we will proceed in the same way to create a view for displaying information of an employee. We create a new View<Employee>.

The following View module is created:

Now we can easily add any properties related to the employee to the view.

In our example an employee has an address and an address contains many properties.

M# makes easy for us to display information from the associated address. We can either select the property "Address" and that will call the ToString() method from the Address instance, or we can create several properties like "Address.City", "Address.Postcode", ...
The rendered view is like this:

Generated code

The generated mark-up is simple, properties are displayed and encoded to HTML:


corresponds to the current instance of the Employee, i.e. John Smith. In our model the Address property is nullable, so in some cases if you call


you can get a NullReferenceException because


is null.
Fortunately M# is smart enough to handle this, even after refactoring our model. The generated code will use the


extension method.

This extension method is equivalent to:

Item.Address == null ? null : Item.Address.City

Data source

By passing the id query string to the page, the datasource will automatically load the employee with this ID. If there is no employee, a NullReferenceException will be thrown.
This allows you to quickly create views without the need to change query strings. Unfortunately this is a bad practise to use "id" in query strings. If tomorrow you need to add other modules (not only views, forms as well) you will have some problems, especially if your modules do not have the same type. For example if you have a view on Employee and a form on Address in the same page you will not know which type corresponds to "id", it could be an Employee or an Address. A good practise is to name your query string with the same name as your class. In our example we will rename "id" to ".Employee" by changing the "Querystring key" attribute of the module.