Programar Web ASP.NET con Razor
1.- Añadir código a una página con @
El carácter @ comienza expresiones en línea, los bloques de una sola declaración, y bloques de varias declaraciones:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Single statement blocks –>
@{ var total = 7; }
@{ var myMessage = “Hello World”; }
<!– Inline expressions –>
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!– Multi-statement block –>
@{
var greeting = “Welcome to our site!”;
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + ” Today is: ” + weekDay;
}
<p>The greeting is: @greetingMessage</p>
</body>
</html>
2.- Incluir los bloques de código entre llaves
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Single statement block. –>
@{ var theMonth = DateTime.Now.Month; }
<p>The numeric value of the current month: @theMonth</p>
<!– Multi-statement block. –>
@{
var outsideTemp = 79;
var weatherMessage = “Hello, it is ” + outsideTemp + ” degrees.”;
}
<p>Today’s weather: @weatherMessage</p>
</body>
</html>
3.- Dentro de un bloque, se termina cada instrucción de código con un punto y coma
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Single-statement block –>
@{ var theMonth = DateTime.Now.Month; }
<!– Multi-statement block –>
@{
var outsideTemp = 79;
var weatherMessage = “Hello, it is ” + outsideTemp + ” degrees.”;
}
<!– Inline expression, so no semicolon –>
<p>Today’s weather: @weatherMessage</p>
</body>
</html>
4.- Usar variables para almacenar datos
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Storing a string –>
@{ var welcomeMessage = “Welcome, new members!”; }
<p>@welcomeMessage</p>
<!– Storing a date –>
@{ var year = DateTime.Now.Year; }
<!– Displaying a variable –>
<p>Welcome to our new members who joined in @year!</p>
</body>
</html>
5.- Incluir los valores de cadena literal entre comillas dobles
Una cadena es una secuencia de caracteres que se tratan como texto.
Para especificar una cadena, se pone entre comillas dobles:
@{ var myString = “This is a string literal”; }
Si la cadena que desea mostrar contiene un carácter de barra invertida (\) o comillas dobles.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Embedding a backslash in a string –>
@{ var myFilePath = @”C:\MyFolder\”; }
<p>The path is: @myFilePath</p>
</body>
</html>
Para incrustar comillas dobles, utilice una cadena literal y repetir las comillas:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<!– Embedding double quotation marks in a string –>
@{ var myQuote = @”The person said: “”Hello, today is Monday.”"”; }
<p>@myQuote</p>
</body>
</html>
6.- El código es sensible a mayúsculas
@{
var lastName = “Smith”;
var LastName = “Jones”;
}
7.- Gran parte de su codificación implica objetos
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Pruebas</title>
</head>
<body>
<table border=”1″>
<tr>
<td>Requested URL</td>
<td>Relative Path</td>
<td>Full Path</td>
<td>HTTP Request Type</td>
</tr>
<tr>
<td>@Request.Url</td>
<td>@Request.FilePath</td>
<td>@Request.MapPath(Request.FilePath)</td>
<td>@Request.RequestType</td>
</tr>
</table>
</body>
</html>
8.- Se puede escribir código que tome decisiones
@{
var result = “”;
if(IsPost)
{
result = “This page was posted using the Submit button.”;
}
else
{
result = “This was the first request for this page.”;
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method=”POST” action=”" >
<input type=”Submit” name=”Submit” value=”Submit”/>
<p>@result</p>
</form>
</body>
</html>
</body>
</html>
9.- Ejemplo de código
@{
var total = 0;
var totalMessage = “”;
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
totalMessage = “Total = ” + total;
}
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Add Numbers</title>
<meta charset=”utf-8″ />
<style type=”text/css”>
body {background-color: beige; font-family: Verdana, Arial;
margin: 50px; }
form {padding: 10px; border-style: solid; width: 250px;}
</style>
</head>
<body>
<p>Enter two whole numbers and then click <strong>Add</strong>.</p>
<form action=”" method=”post”>
<p><label for=”text1″>First Number:</label>
<input type=”text” name=”text1″ />
</p>
<p><label for=”text2″>Second Number:</label>
<input type=”text” name=”text2″ />
</p>
<p><input type=”submit” value=”Add” /></p>
</form>
<p>@totalMessage</p>
</body>
</html>
10.- La sintaxis Razor, Server Code, y ASP.NET
La sintaxis de Razor es una sintaxis de programación sencillo para incrustar código basado en servidor en una página web. En una página web que utiliza la sintaxis Razor, hay dos tipos de contenidos: El contenido de código de cliente y servidor.
Contenido del cliente es el material que está acostumbrado en las páginas web: el formato HTML (elementos), información de estilo como CSS, el script de cliente, como JavaScript, y el texto.
La sintaxis de Razor le permite agregar el código del servidor para este contenido cliente. Si no hay código de servidor en la página, el servidor ejecuta el código en primer lugar, antes de enviar la página al navegador. Ejecutando en el servidor, el código puede realizar tareas que pueden ser mucho más complejas que solo el contenido del cliente, como acceso a bases de datos basadas en servidor. Lo más importante es que el código del servidor puede crear dinámicamente el contenido del cliente – puede generar código HTML o de otros contenidos sobre la marcha y luego enviarlo al navegador, junto con todo el código HTML estático que la página puede contener. Desde el contenido del navegador del cliente perspectiva, que se genera por el código del servidor no es diferente de cualquier contenido de otros clientes. Como ya has visto, el código del servidor que se necesita es bastante simple.
Las páginas web que incluyen la sintaxis Razor tienen una extensión de archivo especial (. Cshtml o vbhtml.). El servidor reconoce estas extensiones, se ejecuta el código que está marcado con la sintaxis de Razor, y luego envía la página al navegador.
La Sintaxis Razor se basa en una tecnología de Microsoft llamada ASP.NET, que a su vez se basa en la plataforma Microsoft. NET Framework. The.NET Framework es un framework grande, la programación completa de Microsoft para el desarrollo de prácticamente cualquier tipo de aplicación informática.
ASP.NET es la parte de. NET Framework, que está específicamente diseñado para la creación de aplicaciones web. Los desarrolladores han utilizado ASP.NET para crear muchos de los sitios web más grandes y de mayor tráfico del mundo. (Cada vez que veas la extensión de nombre de archivo. Aspx como parte de la URL de un sitio, usted sabrá que el sitio fue creado con ASP.NET.)
La sintaxis de Razor le da todo el poder de ASP.NET, pero con una sintaxis simplificada que es más fácil de utilizar si usted es un. A pesar de que esta sintaxis es muy simple de usar, su relación familiar con ASP.NET y. NET Framework significa que a medida que sus sitios web se vuelven más sofisticados, tienen el poder de los frameworks más grandes disponibles para usted.
11.- Combinando Texto, Markup, y Código en Bloques de Código
Escriba el texto en un elemento HTML como <p> </ p> o <em> </ em>:
@if(IsPost) {
// This line has all content between matched <p> tags.
<p>Hello, the time is @DateTime.Now and this page is a postback!</p>
} else {
// All content between matched tags, followed by server code.
<p>Hello <em>stranger</em>, today is: <br /> </p> @DateTime.Now
}
Utilice el operador @: o el elemento <text>.
La salida @: se utiliza para una sola línea de contenido que contienen texto o etiquetas HTML
El elemento <text> encierra varias líneas de producción. Estas opciones son útiles cuando no se desea representar un elemento HTML, como parte de la producción.
@if(IsPost) {
// Plain text followed by an unmatched HTML tag and server code.
@: The time is: <br /> @DateTime.Now
// Server code and then plain text, matched tags, and more text.
@DateTime.Now @:is the <em>current</em> time.
}
Si desea la salida de varias líneas de texto o etiquetas HTML puede preceder a cada línea con @: o puede incluir la línea en un elemento <text>. Al igual que el @: operador, las etiquetas <text> son utilizados por ASP.NET para identificar el contenido del texto.
@if(IsPost) {
// Repeat the previous example, but use <text> tags.
<text>
The time is: <br /> @DateTime.Now
@DateTime.Now is the <em>current</em> time.
</text>
}
@{
var minTemp = 75;
<text>It is the month of @DateTime.Now.ToString(“MMMM”), and
it’s a <em>great</em> day! <br /><p>You can go swimming if it’s at
least @minTemp degrees. </p></text>
}
12.- Código y Comentarios
Empezamos el comentario con @* y cerramos con *@.
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
Comentario dentro de un bloque de código
@{
@* This is a comment. *@
var theVar = 17;
}
13.- Variables y Tipos de datos
@{
// Assigning a string to a variable.
var greeting = “Welcome!”;
// Assigning a number to a variable.
var theCount = 3;
// Assigning an expression to a variable.
var monthlyTotal = theCount + 5;
// Assigning a date value to a variable.
var today = DateTime.Today;
// Assigning the current page’s URL to a variable.
var myPath = this.Request.Url;
// Declaring variables using explicit data types.
string name = “Joe”;
int count = 5;
DateTime tomorrow = DateTime.Now.AddDays(1);
}
@{
// Embedding the value of a variable into HTML markup.
<p>@greeting, friends!</p>
// Using variables as part of an inline expression.
<p>The predicted annual total is: @( monthlyTotal * 12)</p>
// Displaying the page URL with a variable.
<p>The URL to this page is: @myPath</p>
}
14.- Convertir y Testear Tipos de Datos
@{
var total = 0;
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
}
}
15.- El Operador ~.
Raiz del path virtual.
@{
var myImagesFolder = “~/images”;
var myStyleSheet = “~/styles/StyleSheet.css”;
}
16.- Server.MapPath
Convierte el path virtual a físico
@{
var dataFilePath = “~/dataFile.txt”;
}
<!– Displays a physical path C:\Websites\MyWebSite\datafile.txt –>
<p>@Server.MapPath(dataFilePath)</p>
17.- El método Href.
Convierte las rutas que se crea en el código del servidor a path que entiende los navegadores.
@{
var myImagesFolder = “~/images”;
var myStyleSheet = “~/styles/StyleSheet.css”;
}
<!– This code creates the path “../images/Logo.jpg” in the src attribute. –>
<img src=”@Href(myImagesFolder)/Logo.jpg” />
<!– This produces the same result, using a path with ~ –>
<img src=”@Href(“~/images”)/Logo.jpg” />
<!– This creates a link to the CSS file. –>
<link rel=”stylesheet” type=”text/css” href=”@Href(myStyleSheet)” />
18.- Condiciones
@{
var showToday = true;
if(showToday)
{
@DateTime.Today;
}
}
@{
var showToday = false;
if(showToday)
{
@DateTime.Today;
}
else
{
<text>Sorry!</text>
}
}
También podemos utilizar else if
@{
var theBalance = 4.99;
if(theBalance == 0)
{
<p>You have a zero balance.</p>
}
else if (theBalance > 0 && theBalance <= 5)
{
<p>Your balance of $@theBalance is very low.</p>
}
else
{
<p>Your balance is: $@theBalance</p>
}
}
Otro ejemplo:
@{
var weekday = “Wednesday”;
var greeting = “”;
switch(weekday)
{
case “Monday”:
greeting = “Ok, it’s a marvelous Monday”;
break;
case “Tuesday”:
greeting = “It’s a tremendous Tuesday”;
break;
case “Wednesday”:
greeting = “Wild Wednesday is here!”;
break;
default:
greeting = “It’s some other day, oh well.”;
break;
}
<p>Since it is @weekday, the message for today is: @greeting</p>
}
19.- Iteraciones
Utilizamos @for
@for(var i = 10; i < 21; i++)
{
<p>Line #: @i</p>
}
En este caso utilizamos @foreach
@foreach (var myItem in Request.ServerVariables)
{
<li>@myItem</li>
}
Un While
@{
var countNum = 0;
while (countNum < 50)
{
countNum += 1;
<p>Line #@countNum: </p>
}
}
20.- Objeto Request
@{
var path = Request.FilePath;
}
@{
var path1 = this.Request.FilePath;
}
@{
// Access the page’s Request object to retrieve the Url.
var pageUrl = this.Request.Url;
}
<a href=”@pageUrl”>My page</a>
21.- Colecciones de Objetos
<ul>
@* Array block 1: Declaring a new array using braces. *@
@{
<h3>Team Members</h3>
string[] teamMembers = {“Matt”, “Joanne”, “Robert”, “Nancy”};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
</ul>
Otro ejemplo
@{
string[] teamMembers = {“Matt”, “Joanne”, “Robert”, “Nancy”};
<p>The number of names in the teamMembers array: @teamMembers.Length </p>
<p>Robert is now in position: @Array.IndexOf(teamMembers, “Robert”)</p>
<p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
<h3>Current order of team members in the list</h3>
foreach (var name in teamMembers)
{
<p>@name</p>
}
<h3>Reversed order of team members in the list</h3>
Array.Reverse(teamMembers);
foreach (var reversedItem in teamMembers)
{
<p>@reversedItem</p>
}
}
Un Diccionario
@{
var myScores = new Dictionary<string, int>();
myScores.Add(“test1″, 71);
myScores.Add(“test2″, 82);
myScores.Add(“test3″, 100);
myScores.Add(“test4″, 59);
}
<p>My score on test 3 is: @myScores["test3"]%</p>
@(myScores["test4"] = 79)
<p>My corrected score on test 4 is: @myScores["test4"]%</p>
22.- Excepciones
@{
var dataFilePath = “~/dataFile.txt”;
var fileContents = “”;
var physicalPath = Server.MapPath(dataFilePath);
var userMessage = “Hello world, the time is ” + DateTime.Now;
var userErrMsg = “”;
var errMsg = “”;
if(IsPost)
{
// When the user clicks the “Open File” button and posts
// the page, try to open the created file for reading.
try {
// This code fails because of faulty path to the file.
fileContents = File.ReadAllText(@”c:\batafile.txt”);
// This code works. To eliminate error on page,
// comment the above line of code and uncomment this one.
//fileContents = File.ReadAllText(physicalPath);
}
catch (FileNotFoundException ex) {
// You can use the exception object for debugging, logging, etc.
errMsg = ex.Message;
// Create a friendly error message for users.
userErrMsg = “A file could not be opened, please contact ”
+ “your system administrator.”;
}
catch (DirectoryNotFoundException ex) {
// Similar to previous exception.
errMsg = ex.Message;
userErrMsg = “A directory was not found, please contact ”
+ “your system administrator.”;
}
}
else
{
// The first time the page is requested, create the text file.
File.WriteAllText(physicalPath, userMessage);
}
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Try-Catch Statements</title>
</head>
<body>
<form method=”POST” action=”" >
<input type=”Submit” name=”Submit” value=”Open File”/>
</form>
<p>@fileContents</p>
<p>@userErrMsg</p>
</body>
</html>