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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
Introducing ASP.NET Web Pages 2 

Mike Pope 

Summary: This set of tutorials gives you an overview of ASP.NET Web Pages 

(version 2) and Razor syntax, a lightweight framework for creating dynamic 

websites. It also introduces WebMatrix, a tool for creating pages and sites. The 

tutorials take you from novice programmer through seeing your site live on the 

Internet. Topics include how to install Microsoft WebMatrix (a set of tools for 

creating sites); how to work with forms; how to display, add, update, and delete 

data; how to create a consistent site layout; and how to publish to the Web. 

Category: Step-by-Step 

Applies to: ASP.NET Web Pages 2 RC, Visual Studio 2012 RC 

Source: ASP.NET site (link to source content) 

E-book publication date: June 2012 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Copyright Β© 2012 by Microsoft Corporation 

All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any 
means without the written permission of the publisher. 

Microsoft and the trademarks listed at 
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the 
Microsoft group of companies. All other marks are property of their respective owners. 

The example companies, organizations, products, domain names, email addresses, logos, people, places, and 
events depicted herein are fictitious. No association with any real company, organization, product, domain name, 
email address, logo, person, place, or event is intended or should be inferred. 

This book expresses the author’s views and opinions. The information contained in this book is provided without 
any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or 
distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this 
book. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

2 

 
 
 
 
 
 
 
Contents 

Tutorial 1: Getting Started ............................................................................................................. 4 
Tutorial 2: Programming Basics ................................................................................................... 19 
Tutorial 3: Displaying Data ........................................................................................................... 39 
Tutorial 4: HTML Form Basics ...................................................................................................... 56 
Tutorial 5: Entering Database Data by Using Forms ...................................................................... 70 
Tutorial 6: Updating Database Data ............................................................................................. 82 
Tutorial 7: Deleting Database Data .............................................................................................. 97 
Tutorial 8: Creating a Consistent Layout .................................................................................... 104 
Tutorial 9: Publishing a Site by Using WebMatrix ....................................................................... 118 
Appendix: Code Listings ............................................................................................................. 127 

This set of tutorials gives you an overview of ASP.NET Web Pages (version 2) and Razor syntax, a 
lightweight framework for creating dynamic websites. It also introduces WebMatrix, a tool for 
creating pages and sites. 

Level: New to ASP.NET Web Pages. 
Skills assumed: HTML, basic cascading style sheets (CSS). 
Prerequisites: Windows XP SP3 or later. (See What Do You Need? later for more details.) 
Downloads: Completed website for the ASP.NET Web Pages introductory tutorial 

Note   This tutorial is based on the ASP.NET Web Pages version 2 RC and Microsoft 
WebMatrix 2 RC. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

3 

 
 
Tutorial 1: Getting Started 

What you'll learn in the first tutorial of the set: 

β€’  What ASP.NET Web Pages technology is and what it's for. 
β€’  What WebMatrix is. 
β€’  How to install everything. 
β€’  How to create a website by using WebMatrix. 

Features/technologies discussed: 

β€’  Microsoft Web Platform Installer. 
β€’  WebMatrix. 
β€’ 

.cshtml pages 

What Should You Know? 

We're assuming that you're familiar with: 

β€’  HTML. No in-depth expertise is required. We won't explain HTML, but we also don't use 
anything complex. We'll provide links to HTML tutorials where we think they're useful. 

β€’  Cascading style sheets (CSS). Same as with HTML. 

β€’  Basic database ideas. If you've used a spreadsheet for data and sorted and filtered the 

data, that's the level of expertise we're generally assuming for this tutorial set. 

We're also assuming that you're interested in learning basic programming. ASP.NET Web Pages 
use a programming language called C#. You don't have to have any background in programming, 
just an interest in it. If you've ever written any JavaScript in a web page before, you've got plenty 
of background. 

Note that if you are familiar with programming, you might find that this tutorial set initially moves 
slowly while we bring new programmers up to speed. As we get past the first few tutorials, 
though, there will be less basic programming to explain and things will move along at a faster clip. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

4 

 
 
What Do You Need? 

Here's what you'll need: 

β€’  A computer that is running Windows 7, Windows Vista SP2, Windows XP SP3, Windows 

Server 2003 SP2, Windows Server 2008, or Windows Server 2008 R2. 

β€’  A live internet connection. 
β€’  Administrator privileges (required for the installation process). 

What Is ASP.NET Web Pages? 

ASP.NET Web Pages is a framework that you can use to create dynamic web pages. A simple 
HTML web page is static; its content is determined by the fixed HTML markup that's in the page. 
Dynamic pages like those you create with ASP.NET Web Pages let you create the page content on 
the fly, by using code. 

Dynamic pages let you do all sorts of things. You can ask a user for input by using a form and then 
change what the page displays or how it looks. You can take information from a user, save it in a 
database, and then list it later. You can send email from your site. You can interact with other 
services on the web (for example, a mapping service) and produce pages that integrate 
information from those sources. 

What Is WebMatrix? 

WebMatrix is a tool that integrates a web page editor, a database utility, a web server for testing 
pages, and features for publishing your website to the Internet. WebMatrix is free, and it's easy to 
install and easy to use. (It also works for just plain HTML pages, as well as for other technologies 
like PHP.)  

You don't actually have to use WebMatrix to work with ASP.NET Web Pages. You can create pages 
by using a text editor, for example, and test pages by using a web server that you have access to. 
However, WebMatrix makes it all very easy, so these tutorials will use WebMatrix throughout.  

About These Tutorials 

This tutorial set is an introduction to how to use ASP.NET Web Pages. There are 9 tutorials total in 
this introductory tutorial set. It's part of a series of tutorial sets that takes you from ASP.NET Web 
Pages novice to creating real, professional-looking websites. 

This first tutorial set concentrates on showing you the basics of how to work with ASP.NET Web 
Pages. When you're done, you can work with additional tutorial sets that pick up where this one 
ends and that explore Web Pages in more depth. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

5 

We deliberately go easy on the in-depth explanations. And whenever we show something, for this 
tutorial set we always chose the way that we think is easiest to understand. Later tutorial sets go 
into more depth and show you more efficient or more flexible approaches (also more fun). But 
those tutorials require you to understand the basics first. 

The tutorial set you've just started covers these features of ASP.NET Web Pages: 

Introduction and getting everything installed. (That's in the tutorial you're reading.) 

β€’ 
β€’  The basics of ASP.NET Web Pages programming. 
β€’  Creating a database. 
β€’  Creating and processing a user input form. 
β€’  Adding, updating, and deleting data in the database. 

At any point you can publish (deploy) your site to a hosting provider. We'll talk about that at the 
end of this tutorial set and link you to a tutorial on how to do that. 

What Will You Create? 

This tutorial set and subsequent ones revolve around a website where you can list movies that 
you like. You'll be able to enter movies, edit them, and list them. Here are a couple of the pages 
you'll create in this tutorial set. The first one shows the movie listing page that you'll create: 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

6 

 
And here's the page that lets you add new movie information to your site: 

Subsequent tutorial sets build on this set and add more functionality, like uploading pictures, 
letting people log in, sending email, and integrating with social media.  

Ok, let's get started. 

Note   You can download a finished version of the website that's described in these 
tutorials. 

Installing Everything 

You can install everything by using the Web Platform Installer from Microsoft. In effect, you install 
the installer, and then use it to install everything else. 

To use Web Pages, you have to be have at least Windows XP with SP3 installed, or Windows 
Server 2008 or later. 

On the Web Pages page of the ASP.NET website, click Install WebMatrix.  

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

7 

 
This button takes you to the Web Platform Installer page on the Microsoft.com site.  

If the download doesn't start automatically, click the Install Now button. Then click Run. (If you 
want to save the installer, click Save and then run the installer from the folder where you saved 
it.) 

The Web Platform Installer appears, ready to install WebMatrix. Click Install. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

8 

 
 
 
The installation process figures out what it has to install on your computer and starts the process. 
Depending on what exactly has to be installed, the process can take anywhere from a few 
moments to several minutes. 

Hello, WebMatrix 

When it's done, the installation process can launch WebMatrix automatically. If it doesn't, in 
Windows, from the Start menu, launch Microsoft WebMatrix. 

In Windows, start Microsoft WebMatrix.  

To begin, you'll create a blank website and add a page. In the next tutorial set, you'll use one of 
the built-in website templates. 

In the start window, click Templates. Templates are prebuilt files and pages for different types of 
websites. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

9 

 
 
In the Quick Start window, select Empty Site and name the new site "WebPagesMovies".  

Click Next. 

WebMatrix creates and opens the site: 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

10 

 
 
At the top, there's a Quick Access Toolbar and a ribbon, like in Microsoft Office 2010. At the 
bottom left, you see the workspace selector where you switch between tasks (Site, Files, 
Databases, Reports). On the right is the content pane for the editor and for reports. And across 
the bottom you'll occasionally see a notification bar for messages. 

You'll learn more about WebMatrix and its features as you go through these tutorials. 

Creating a Web Page 

To become familiar with WebMatrix and ASP.NET Web Pages, you'll create a simple page.  

In the workspace selector, select the Files workspace. This workspace lets you work with files and 
folders. The left pane shows the file structure of your site. The ribbon changes to show file-related 
tasks. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

11 

 
In the ribbon, click the arrow under New and then click New File. 

WebMatrix displays a list of file types. Select CSHTML, and in the Name box, type "HelloWorld". A 
CSHTML page is an ASP.NET Web Pages page. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

12 

 
 
 
 
Click OK. 

WebMatrix creates the page and opens it in the editor. 

As you can see, the page contains mostly ordinary HTML markup, except for a block at the top 
that looks like this:  

@{  

} 

That's for adding code, as you'll see shortly. 

Notice that the different parts of the page β€” the element names, attributes, and text, plus the 
block at the top β€” are all in different colors. This is called syntax highlighting, and it makes it 
easier to keep everything clear. It's one of the features that makes it easy to work with web pages 
in WebMatrix.  

Add content for the <head> and <body> elements like in the following example. (If you want, you 
can just copy the following block and replace the entire existing page with this code.) 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

13 

 
 
 
 
 
 
 
 
@{ 

} 

<!DOCTYPE html> 

<html lang="en"> 
<head> 
<meta charset="utf-8" /> 
<title>Hello World Page</title> 
</head> 
<body> 
<h1>Hello World Page</h1> 
<p>Hello World!</p> 
</body> 
</html> 

In the Quick Access Toolbar or in the File menu, click Save. 

Testing the Page 

In the Files workspace, right-click the HelloWorld.cshtml page and then click Launch in browser.  

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

14 

 
 
 
 
WebMatrix starts a built-in web server (IIS Express) that you can use to test pages on your 
computer. (Without IIS Express in WebMatrix, you'd have to publish your page to a web server 
somewhere before you could test it.) The page is displayed in your default browser. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

15 

 
 
 
 
 
 
localhost and port numbers 

Notice that when you test a page in WebMatrix, the URL in the browser is something like 
http://localhost:33651/HelloWorld.cshtml. The name localhost refers to a local server, meaning 
that the page is served by a web server that's on your own computer. As noted, WebMatrix 
includes a web server program named IIS Express that runs when you launch a page.  

The number after localhost (for example, localhost:33651) refers to a port number on your 
computer. This is the number of the "channel" that IIS Express uses for this particular website. 
The port number is selected at random from the range 1024 through 65536 when you create your 
site, and it's different for every site that you create. (When you test your own site, the port 
number will almost certainly be a different number than 33561.) By using a different port for each 
website, IIS Express can keep straight which of your sites it's talking to. 

Later when you publish your site to a public web server, you no longer see localhost in the URL. At 
that point, you'll see a more typical URL like http://myhostingsite/mywebsite/HelloWorld.cshtml 
or whatever the page is. You'll learn more about publishing a site later in this tutorial series. 

Adding Some Server-Side Code 

Close the browser and go back to the page in WebMatrix. 

Add a line to the code block so that it looks like the following code: 

@{ 
   var currentDateTime = DateTime.Now; 
} 

This is a little bit of Razor code. It's probably clear that it gets the current date and time and puts 
that value into a variable named currentDateTime. You'll read more about Razor syntax in the next 
tutorial. 

In the body of the page, after the <p>Hello World!</p> element, add the following: 

<p>Right now it's @currentDateTime</p> 

This code gets the value that you put into the currentDateTime variable at the top and inserts it 
into the markup of the page. The @ character marks the ASP.NET Web Pages code in the page. 

Run the page again (WebMatrix saves the changes for you before it runs the page). This time you 
see the date and time in the page.  

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

16 

Wait a few moments and then refresh the page in the browser. The date and time display is 
updated.  

In the browser, look at the page source. It looks like the following markup: 

<!DOCTYPE html> 

<html lang="en"> 
<head> 
<meta charset="utf-8" /> 
<title>Hello World Page</title> 
</head> 
<body> 
<h1>Hello World Page</h1> 
<p>Hello World!</p> 
<p>Right now it's 1/18/2012 2:49:50 PM</p> 
</body> 
</html> 

Notice that the @{ } block at the top isn't there. Also notice that the date and time display shows 
an actual string of characters (1/18/2012 2:49:50 PM or whatever), not @currentDateTime like you 
had in the .cshtml page. What happened here is that when you ran the page, ASP.NET processed 
all the code (very little in this case) that was marked with @. The code produces output, and that 
output was inserted into the page.  

This Is What ASP.NET Web Pages Are About 

When you read that ASP.NET Web Pages produces dynamic web content, what you've seen here 
is the idea. The page you just created contains the same HTML markup that you've seen before. It 
can also contain code that can perform all sorts of tasks. In this example, it did the trivial task of 
getting the current date and time. As you saw, you can intersperse code with the HTML to 
produce output in the page. When someone requests a .cshtml page in the browser, ASP.NET 
processes the page while it's still in the hands of the web server. ASP.NET inserts the output of the 
code (if any) into the page as HTML. When the code processing is done, ASP.NET sends the 
resulting page to the browser. All the browser ever gets is HTML. Here's a diagram: 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

17 

 
 
The idea is simple, but there are many interesting tasks that the code can perform, and there are 
many interesting ways in which you can dynamically add HTML content to the page. And ASP.NET 
.cshtml pages, like any HTML page, can also include code that runs in the browser itself (JavaScript 
and jQuery code). You'll explore all of these things in this tutorial set and in subsequent ones. 

Coming Up Next 

In the next tutorial in this series, you explore ASP.NET Web Pages programming a little more. 

Additional Resources 

β€’  HTML Tutorial on the W3Schools site. 

Introducing ASP.NET Web Pages 2 

Tutorial 1: Getting Started 

18 

 
Tutorial 2: Programming Basics 

This tutorial gives you an overview of how to program in ASP.NET Web Pages with Razor syntax. 

What you'll learn: 

Some basic C#, which is the programming language you'll use. 
Some fundamental programming concepts for Web Pages. 

β€’  The basic "Razor" syntax that you use for programming in ASP.NET Web Pages. 
β€’ 
β€’ 
β€’  How to install packages (components that contain prebuilt code) to use with your site. 
β€’  How to use helpers to perform common programming tasks. 

Features/technologies discussed: 

β€’  NuGet and the package manager. 
β€’  The Twitter helper. 

This tutorial is primarily an exercise in introducing you to the programming syntax that you'll use 
for ASP.NET Web Pages. You'll learn about Razor syntax and code that's written in the C# 
programming language. You got a glimpse of this syntax in the previous tutorial; in this tutorial 
we'll explain the syntax more.  

We promise that this tutorial involves the most programming that you'll see in a single tutorial, 
and that it's the only tutorial that is only about programming. In the remaining tutorials in this set, 
you'll actually create pages that do interesting things. 

You'll also learn about helpers. A helper is a component β€” a packaged-up piece of code β€” that 
you can add to a page. The helper performs work for you that otherwise might be tedious or 
complex to do by hand. 

Creating a Page to Play with Razor 

In this section you'll play a bit with Razor so you can get a sense of the basic syntax. 

Start WebMatrix if it's not already running. You'll use the website you created in the previous 
tutorial (Getting Started). To reopen it, click Open Site and choose My Sites: 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

19 

Choose the WebPagesMovies site, and then click OK. 

Select the Files workspace. 

In the ribbon, click New to create a page. Select CSHTML and name the new page 
TestRazor.cshtml. 

Click OK. 

Copy the following into the file, completely replacing what's there already. 

Note   When you copy code or markup from the examples into a page, the indentation and 
alignment might not be the same as in the tutorial. Indentation and alignment don't affect 
how the code runs, though.  

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

20 

 
 
 
 
 
@{ 
   // Working with numbers 
   var a = 4; 
   var b = 5; 
   var theSum = a + b; 

   // Working with characters (strings) 
   var technology = "ASP.NET"; 
   var product ="Web Pages"; 

   // Working with objects 
   var rightNow = DateTime.Now; 
} 

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>Testing Razor Syntax</title> 
<meta charset="utf-8" /> 
<style> 
    body {font-family:Verdana; margin-left:50px; margin-top:50px;} 
    div {border: 1px solid black; width:50%; margin:1.2em;padding:1em;} 
    span.bright {color:red;} 
</style> 
</head> 
<body> 
<h1>Testing Razor Syntax</h1> 
<form method="post"> 

<div> 
<p>The value of <em>a</em> is @a.  The value of <em>b</em> is @b.  
<p>The sum of <em>a</em> and <em>b</em> is <strong>@theSum</strong>.</p> 
<p>The product of <em>a</em> and <em>b</em> is <strong>@(a*b)</strong>.</p> 
</div> 

<div> 
<p>The technology is @technology, and the product is @product.</p> 
<p>Together they are <span class="bright">@(technology + " " + 
 product)</span></p> 
</div> 

<div> 
<p>The current date and time is: @rightNow</p> 
<p>The URL of the current page is<br/><br/><code>@Request.Url</code></p> 
</div> 

</form> 
</body> 
</html> 

Examining the Example Page 

Most of what you see is ordinary HTML. However, at the top there's this code block: 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

21 

 
 
 
 
 
 
 
 
@{ 
   // Working with numbers. 
   var a = 4; 
   var b = 5; 
   var theSum = a + b; 

   // Working with characters (strings). 
   var technology = "ASP.NET"; 
   var product ="Web Pages"; 

   // Working with objects. 
   var rightNow = DateTime.Now; 
} 

Notice the following things about this code block: 

β€’  The @ character tells ASP.NET that what follows is Razor code, not HTML. ASP.NET will 

treat everything after the @ character as code until it runs into some HTML again. (In this 
case, that's the <!DOCTYPE> element. 

β€’  The braces ( { and } ) enclose a block of Razor code if the code has more than one line. 

The braces tell ASP.NET where the code for that block starts and ends. 

β€’  The // characters mark a comment β€” that is, a part of the code that won't execute. 

β€’  Each statement has to end with a semicolon (;). (Not comments, though.) 

β€’  You can store values in variables, which you create (declare) with the keyword var.When 

you create a variable, you give it a name, which can include letters, numbers, and 
underscore (_). Variable names can't start with a number and can't use the name of a 
programming keyword (like var). 

β€’  You enclose character strings (like "ASP.NET" and "Web Pages") in quotation marks. (They 

must be double quotation marks.) Numbers are not in quotation marks.  

β€’  Whitespace outside of quotation marks doesn't matter. Line breaks mostly don't matter; 
the exception is that you can't split a string in quotation marks across lines. Indentation 
and alignment don't matter.  

Something that's not obvious from this example is that all code is case sensitive. This means that 
the variable TheSum is a different variable than variables that might be named theSum or thesum. 
Similarly, var is a keyword, but Var is not.  

Objects and properties and methods 

Then there's the expression DateTime.Now. In simple terms, DateTime is an object. An object is a 
thing that you can program withβ€”a page, a text box, a file, an image, a web request, an email 
message, a customer record, etc. Objects have one or more properties that describe their 
characteristics. A text box object has a Text property (among others), a request object has a 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

22 

 
 
Urlproperty (and others), an email message has a From property and a To property, and so on. 
Objects also have methods that are the "verbs" they can perform. You'll be working with objects a 
lot.  

As you can see from the example, DateTime is an object that lets you program dates and times. It 
has a property named Now that returns the current date and time.  

Using code to render markup in the page 

In the body of the page, notice the following: 

<div> 
<p>The value of <em>a</em> is @a.  The value of <em>b</em> is @b.  
<p>The sum of <em>a</em> and <em>b</em> is <strong>@theSum</strong>.</p> 
<p>The product of <em>a</em> and <em>b</em> is <strong>@(a*b)</strong>.</p> 
</div> 

<div> 
<p>The technology is @technology, and the product is @product.</p> 
<p>Together they are <span class="bright">@(technology + " " +  
product)</span></p> 
</div> 

<div> 
<p>The current date and time is: @rightNow</p> 
<p>The URL of the current page is<br/><br/><code>@Request.Url</code></p> 
</div> 

Again, the @ character tells ASP.NET that what follows is code, not HTML. In the markup you can 
add @ followed by a code expression, and ASP.NET will render the value of that expression right at 
that point. In the example, @a will render whatever the value is of the variable named a, @product 
renders whatever is in the variable named product, and so on. 

You're not limited to variables, though. In a few instances here, the @ character precedes an 
expression: 

β€’ 

β€’ 

β€’ 

@(a*b) renders the product of whatever is in the variables a and b. (The * operator means 
multiplication.) 
@(technology + " " + product) renders the values in the variables technology and 
product after concatenating them and adding a space in between. The operator (+) for 
concatenating strings is the same as the operator for adding numbers. ASP.NET can 
usually tell whether you're working with numbers or with strings and does the right thing 
with the + operator. 
@Request.Url renders the Url property of the Request object. The Request object contains 
information about the current request from the browser, and of course the Url property 
contains the URL of that current request. 

The example is also designed to show you that you can do work in different ways. You can do 
calculations in the code block at the top, put the results into a variable, and then render the 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

23 

 
 
variable in markup. Or you can do calculations in an expression right in the markup. The approach 
you use depends on what you're doing and, to some extent, on your own preference. 

Seeing the code in action 

Right-click the name of the file and then choose Launch in browser. You see the page in the 
browser with all the values and expressions resolved in the page. 

(Remember that the URL that you see in the browser might use a different port number than 
what you see in these screenshots. Instead of locahost:56011, you'll see localhost followed by a 
different number.) 

Look at the source in the browser. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

24 

 
As you expect from your experience in the previous tutorial, none of the Razor code is in the page. 
All you see are the actual display values. When you run a page, you're actually making a request 
to the web server that's built into WebMatrix. When the request is received, ASP.NET resolves all 
the values and expressions and renders their values into the page. It then sends the page to the 
browser. 

Razor and C# 

Up to now we've said that you're working with Razor syntax. That's true, but it's not the complete 
story. The actual programming language you're using is called C#. C# was created by Microsoft 
over a decade ago and has become one of the primary programming languages for creating 
Windows apps. All the rules you've seen about how to name a variable and how to create 
statements and so on are actually all rules of the C# language. 

Razor refers more specifically to the small set of conventions for how you embed this code into a 
page. For example, the convention of using @ to mark code in the page and using @{ } to embed a 
code block is the Razor aspect of a page. Helpers are also considered to be part of Razor. Razor 
syntax is used in more places than just in ASP.NET Web Pages. (For example, it's used in ASP.NET 
MVC views as well.) 

We mention this because if you look for information about programming ASP.NET Web Pages, 
you'll find lots of references to Razor. However, a lot of those references don't apply to what 
you're doing and might therefore be confusing. And in fact, many of your programming questions 
are really going to be about either working with C# or working with ASP.NET. So if you look 
specifically for information about Razor, you might not find the answers you need. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

25 

 
Adding Some Conditional Logic 

One of the great features about using code in a page is that you can change what happens based 
on various conditions. In this part of the tutorial, you'll play around with some ways to change 
what's displayed in the page. 

The example will be simple and somewhat contrived so that we can concentrate on the 
conditional logic. The page you'll create will do this: 

β€’ 

Show different text on the page depending on whether it's the first time the page is 
displayed or whether you've clicked a button to submit the page. That will be the first 
conditional test. 

β€’  Display the message only if a certain value is passed in the query string of the URL 

(http://...?show=true). That will be the second conditional test. 

In WebMatrix, create a page and name it TestRazorPart2.cshtml. (In the ribbon, click New, choose 
CSHTML, name the file, and then click OK.) 

Replace the contents of that page with the following: 

@{ 
   var message = "This is the first time you've requested the page."; 
} 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>Testing Razor Syntax - Part 2</title> 
<meta charset="utf-8" /> 
<style> 
      body {font-family:Verdana; margin-left:50px; margin-top:50px;} 
      div {border: 1px solid black; width:50%; margin:1.2em;padding:1em;} 
</style> 
</head> 
<body> 
<h1>Testing Razor Syntax - Part 2</h1> 
<form method="post"> 
<div> 
<p>@message</p> 
<p><input type="submit" value="Submit" /></p> 
</div> 
</form> 
</body> 
</html> 

The code block at the top initializes a variable named message with some text. In the body of the 
page, the contents of the message variable are displayed inside a <p> element. The markup also 
contains an <input> element to create a Submit button. 

Run the page to see how it works now. For now, it's basically a static page, even if you click the 
Submit button. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

26 

Go back to WebMatrix. Inside the code block, add the following code after the line that initializes 
message: 

if(IsPost){ 
   message = "Now you've submitted the page."; 
} 

The if{ } block 

What you just added was an if condition. In code, the if condition has a structure like this: 

if(some condition){ 
One or more statements here that run if the condition is true; 
}  

The condition to test is in parentheses. It has to be a value or an expression that returns true or 
false. If the condition is true, ASP.NET runs the statement or statements that are inside the 
braces. (Those are the then part of the if-then logic.) If the condition is false, the block of code is 
skipped. 

Here are a few examples of conditions you can test in an if statement: 

if( currentValue > 12 ){ ... } 

if( dueDate <= DateTime.Today ) { ... } 

if( IsDone == true ) { ... } 

if( IsPost ) { ... } 

if( !IsPost ) { ... } 

if(a != 0) { ... } 

if( fileProcessingIsDone != true && displayMessage == false ) { ... }  

You can test variables against values or against expressions by using a logical operator or 
comparison operator: equal to (==), greater than (>), less than (<), greater than or equal to (>=), 
and less than or equal to (<=). The != operator means not equal to β€” for example, if(a != 0) 
means if a is not equal to 0. 

Note   Make sure you notice that the comparison operator for equals to (==) is not the 
same as =. The = operator is used only to assign values (var a=2). If you mix these 
operators up, you'll either get an error or you'll get some strange results.  

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

27 

 
 
 
 
 
 
To test whether something is true, the complete syntax is if(IsDone == true). But you can also 
use the shortcut if(IsDone). If there's no comparison operator, ASP.NET assumes that you're 
testing for true. 

The ! operator by itself means a logical NOT. For example, the condition if(!IsPost) means if 
IsPost is not true.  

You can combine conditions by using a logical AND (&& operator) or logical OR (|| operator). For 
example, the last of the if conditions in the preceding examples means if FileProcessingIsDone is 
set to true AND displayMessage is set to false.  

The else block 

One final thing about if blocks: an if block can be followed by an else block. An else block is 
useful is you have to execute different code when the condition is false. Here's a simple example: 

var message = ""; 
if(errorOccurred == true) 
{ 
    message = "Sorry, an error occurred.";  
} 
else 
{ 
     message = "The process finished without errors!"; 
} 

You'll see some examples in later tutorials in this series where using an else block is useful. 

Testing whether the request is a submit (post) 

There's more, but let's get back to the example, which has the condition if(IsPost){ ... }. 
IsPost is actually a property of the current page. The first time the page is requested, IsPost 
returns false. However, if you click a button or otherwise submit the page β€” that is, you post it β€” 
IsPost returns true. So IsPost lets you determine whether you're dealing with a form submission. 
(In terms of HTTP verbs, if the request is a GET operation, IsPost returns false. If the request is a 
POST operation, IsPost returns true.) In a later tutorial you'll work with input forms, where this 
test becomes particularly useful.  

Run the page. Because this is the first time you're requested the page, you see "This is the first 
time you've requested the page". That string is the value that you initialized the message variable 
to. There's an if(IsPost) test, but that returns false at the moment, so the code inside the if 
block doesn't run. 

Click the Submit button. The page is requested again. As before, the message variable is set to 
"This is the first time ...".But this time, the test if(IsPost) returns true, so the code inside the 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

28 

ifblock runs. The code changes the value of the message variable to a different value, which is 
what's rendered in the markup. 

Now add an if condition in the markup. Below the <p> element that contains the Submit button, 
add the following markup: 

@if(IsPost){ 
<p>You submitted the page at @DateTime.Now</p> 
} 

You're adding code inside the markup, so you have to start with @. Then there's an if test similar 
to the one you added earlier up in the code block. Inside the braces, though, you're adding 
ordinary HTML β€” at least, it's ordinary until it gets to @DateTime.Now. This is another little bit of 
Razor code, so again you have to add @ in front of it.  

The point here is that you can add if conditions in both the code block at the top and in the 
markup.  If you use an if condition in the body of the page, the lines inside the block can be 
markup or code. In that case, and as is true anytime you mix markup and code, you have to use @ 
to make it clear to ASP.NET where the code is. 

Run the page and click Submit.This time you not only see a different message when you submit 
("Now you've submitted ..."), but you see a new message that lists the date and time.  

Testing the value of a query string 

One more test. This time, you'll add an if block that tests a value named show that might be 
passed in the query string.(Like this: http://localhost:43097/TestRazorPart2.cshtml?show=true) 
You'll change the page so that the message you've been displaying ("This is the first time ...", etc.) 
is only displayed if the value of show is true. 

At the bottom (but inside) the code block at the top of the page, add the following: 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

29 

 
 
var showMessage = false; 
if(Request.QueryString["show"].AsBool() == true){ 
    showMessage = true; 
} 

The complete code block now looks like the following example. (Remember that when you copy 
the code into your page, the indentation might look different. But that doesn't affect how the 
code runs.) 

@{ 
   var message = "This is the first time you've requested the page."; 

   if(IsPost){ 
      message = "Now you've submitted the page."; 
   } 

   var showMessage = false; 
   if(Request.QueryString["show"].AsBool() == true){ 
     showMessage = true; 
   } 
} 

The new code in the block initializes a variable named showMessage to false. It then does an if test 
to look for a value in the query string. When you first request the page, it has a URL like this one: 

http://localhost:43097/TestRazorPart2.cshtml 

The code determines whether the URL contains a variable named show in the query string, like this 
version of the URL: 

http://localhost:43097/TestRazorPart2.cshtml?show=true 

The test itself looks at the QueryString property of the Request object. If the query string contains 
an item named show, and if that item is set to true, the if block runs and sets the showMessage 
variable to true. 

There's a trick here, as you can see. Like the name says, the query string is a string. However, you 
can only test for true and false if the value you're testing is a Boolean (true/false) value. Before 
you can test the value of the show variable in the query string, you have to convert it to a Boolean 
value. That's what the AsBool method does β€” it takes a string as input and converts it to a 
Boolean value. Clearly, if the string is "true", the AsBool method converts that value to true.If the 
value of the string is anything else, AsBool returns false. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

30 

 
 
 
Data Types and As( ) Methods 

We've only said so far that when you create a variable, you use the keyword var. That's not the 
entire story, though. In order to manipulate values β€” to add numbers, or concatenate strings, or 
compare dates, or test for true/false β€” C# has to work with an appropriate internal 
representation of the value. C# can usually figure out what that representation should be (that is, 
what type the data is) based on what you're doing with the values. Now and then, though, it can't 
do that. If not, you have to help out by explicitly indicating how C# should represent the data. The 
AsBool method does that β€” it tells C# that a string value of "true" or "false" should be treated as 
a Boolean value. Similar methods exist to represent strings as other types as well, like AsInt (treat 
as an integer), AsDateTime (treat as a date/time), AsFloat (treat as a floating-point number), and 
so on. When you use these As( ) methods, if C# can't represent the string value as requested, 
you'll see an error. 

In the markup of the page, remove or comment out this element (here it's shown commented 
out): 

<!-- <p>@message</p> --> 

Right where you removed or commented out that text, add the following:  

@if(showMessage){ 
<p>@message</p> 
}    

The if test says that if the showMessage variable is true, render a <p> element with the value of the 
message variable. 

Summary of your conditional logic 

In case you're not entirely sure of what you've just done, here's a summary.  

β€’  The message variable is initialized to a default string ("This is the first time ..."). 
β€’ 

If the page request is the result of a submit (post), the value of message is changed to 
"Now you've submitted ..." 

β€’  The showMessage variable is initialized to false. 
β€’ 
β€’ 

If the query string contains ?show=true , the showMessage variable is set to true.  
In the markup, if showMessage is true, a <p> element is rendered that shows the value of 
message. (If showMessage is false, nothing is rendered at that point in the markup.)  
In the markup, if the request is a post, a <p> element is rendered that displays the date 
and time. 

β€’ 

Run the page. There's no message, because showMessage is false, so in the markup the 
if(showMessage) test returns false. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

31 

Click Submit. You see the date and time, but still no message. 

In your browser, go to the URL box and add the following to the end of the URL: ?show=true and 
then press Enter. 

The page is displayed again. (Because you changed the URL, this is a new request, not a submit.) 
Click Submit again. The message is displayed again, as is the date and time. 

In the URL, change ?show=true to ?show=false and press Enter. Submit the page again. The page is 
back to how you started β€” no message. 

As noted earlier, the logic of this example is a little contrived. However, if is going to come up in 
many of your pages, and it will take one or more of the forms you've seen here. 

Installing a Helper (Displaying a Twitter Feed) 

Some tasks that people often want to do on web pages require a lot of code or require extra 
knowledge. Examples: displaying a chart for data; putting a Facebook "Like" button on a page; 
sending email from your website; cropping or resizing images; using PayPal for your site. To make 
it easy to do these kinds of things, ASP.NET Web Pages lets you use helpers. Helpers are 
components that you install for a site and that let you perform typical tasks by using just a few 
lines of Razor code.  

ASP.NET Web Pages has a few helpers built in. However, many helpers are available in packages 
(add-ins) that are provided using the NuGet package manager. NuGet lets you select a package to 
install and then it takes care of all the details of the installation.  

In this part of the tutorial, you'll install a helper that lets you manage a Twitter feed. You'll learn 
two things. One is how to find and install a helper. You'll also learn how a helper makes it easy to 
do something you'd otherwise need to do by using a lot of code you'd have to write yourself. 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

32 

 
 
In WebMatrix, click the Gallery button.  

This launches the NuGet package manager and displays available packages. (Not all of the 
packages are helpers; some add functionality to WebMatrix itself, some are additional templates, 
and so on.) 

In the search box, enter "Twitter". NuGet shows the packages that have Twitter functionality. 
(The link underneath the package icon links to details about that package.)  

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

33 

 
 
 
Select the Twitter.Helper package and then click Install to launch the installer. When it's 
done,you see a message in the notification area at the bottom of the screen. 

That's it. NuGet downloads and installs everything, including any additional components that 
might be required (dependencies). Since this is the first time you've installed a helper, NuGet also 
creates folders in your website for the code that makes up the helper. 

If for some reason you have to uninstall a helper, the process is very similar. Click the Gallery 
button, click the Installed tab, and pick the package you want to uninstall.  

Using a Helper in a Page 

Now you'll use the Twitter helper that you just installed. The process for adding a helper to a page 
is similar for most helpers. 

In WebMatrix, create a page and name it TwitterTest.cshml. (You're creating a special page to test 
the helper, but you can use helpers in any page in your site.) 

Inside the <body> element, add a <div> element. Inside the <div> element, type this: 

@TwitterGoodies. 

The @ character is the same character you've been using to mark Razor code. TwitterGoodies is 
the helper object that you're working with.  

As soon as you type the period (.), WebMatrix displays a list of methods (functions) that the 
TwitterGoodies helper makes available: 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

34 

 
 
This feature is known as IntelliSense. It helps you code by providing context-appropriate choices. 
IntelliSense works with HTML, CSS, ASP.NET code, JavaScript, and other languages that are 
supported in WebMatrix. It's another feature that makes it easier to develop web pages in 
WebMatrix. 

Press S on the keyboard, and you see that IntelliSense finds the Search method: 

Press Tab. IntelliSense inserts the selected method (Search) for you. Type an open parenthesis ( ( 
), then the string "webmatrix" in quotation marks, then a closing parenthesis ( ) ). When you're 
done, the line looks like this: 

@TwitterGoodies.Search("webmatrix") 

The Search method finds tweets that contain the string that you specify β€” in this case, it will look 
for tweets that mention "webmatrix". (Either in text or in hashtags.) 

Run the page. You see a Twitter feed. (It might take a few moments for the feed to start 
populating.) 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

35 

 
To get an idea of what the helper is doing for you, view the source of the page in the 
browser.Along with the HTML that you had in your page, you see a block of JavaScript code that 
looks roughly like the following block. (It might be all on one line or otherwise compressed.) 

<script> new TWTR.Widget({ version: 2, type: 'search', search: 'webmatrix', interval: 

6000, title: '', subject: '', width: 250, height: 300, theme: { shell: { background: 

'#8ec1da', color: '#ffffff' }, tweets: { background: '#ffffff', color: '#444444', links: 

'#1985b5' } }, features: { scrollbar: false, loop: true, live: true, hashtags: true, 

timestamp: true, avatars: true, toptweets: true, behavior: 'all' } }).render().start(); 
</script> 

This is code that the helper rendered into the page at the place where you had 
@TwitterGoodies.Search. (There's also some markup that's not shown here.) The helper took the 
information you provided and generated the code that talks directly to Twitter in order to get 
back the Twitter feed that you see. If you know the Twitter programming interface (API), you can 
create this code yourself. But because the helper can do it for you, you don't have to know the 
details of how to communicate with Twitter. And even if you are familiar with the Twitter API, it's 
a lot easier to include the TwitterGoodies helper on the page and let it do the work. 

Return to the page. At the bottom, inside the <body> element, add the following code. Substitute 
your own Twitter account name if you have one. 

<div> 
    @TwitterGoodies.FollowButton("microsoft") 
</div> 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

36 

 
This code calls the FollowButton method of the TwitterGoodies helper. As you can guess, the 
method adds a Follow Me on Twitter button. You pass a Twitter name to this method to indicate 
who to follow.  

Run the page and you see the Follow Me button: 

Click it, and you go to the Twitter page for the user you specified.  

As before, you can look at the source of the page in the browser to see what the Twitter helper 
generated for you. This time the code looks something like the following example: 

<a href="http://www.twitter.com/microsoft"><img src="http://twitter-
badges.s3.amazonaws.com/follow_me-a.png" alt="Follow microsoft on Twitter"/></a> 

Again, you could have written this code yourself, but the helper makes it much easier. 

Server-Side (Razor) and Client-Side (JavaScript) Programming 

How does Razor code in an ASP.NET Web Pages relate to JavaScript code that runs in the 
browser? If you've got experience with JavaScript, you might realize as you work with these 
tutorials that many of the tasks could also be done in JavaScript. That's true, especially with the 
simple examples you've seen so far. 

A .cshtml page can contain both Razor code and JavaScript code. The traditional division of labor 
has been that server code handled tasks that it made sense to run on the server. This included 
accessing resources like a shared database and performing various types of business logic. In 
contrast, client code has typically been used to create a rich user experience. Pop-up calendars, 
sliders, animations, and many other UI effects are created by client code, and can all be done 
easily using JavaScript libraries (especially jQuery).  

These days the distinction has blurred a little because client code libraries now let you 
communicate with the server in ways that formerly could only be done in server code. In general, 
though, it's still useful to think of server code (Razor and C#) as being for back-end work and client 
code (JavaScript) as useful for UI. In subsequent tutorial sets you'll learn how to integrate 
JavaScript into a .cshtml page for just this purpose, namely to create a lively user experience.  

Coming Up Next 

To keep this tutorial short, we had to focus on only a few basics. Naturally, there's a lot more to 
Razor and C#. You'll learn more as you go through these tutorials. If you're interested in learning 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

37 

 
more about the programming aspects of Razor and C# right now, you can read a more thorough 
introduction here:Introduction to ASP.NET Web Programming Using the Razor Syntax.  

The next tutorial introduces you to working with a database. In that tutorial, you'll begin creating 
the sample application that lets you list your favorite movies. 

Additional Resources 

β€’  Complete Listing for Test Razor Page 
β€’  Complete Listing for TestRazorPart2 Page 
β€’  Complete Listing for TwitterTest Page 
β€’ 

Introduction to ASP.NET Web Programming Using the Razor Syntax 

Introducing ASP.NET Web Pages 2 

Tutorial 2: Programming Basics 

38 

Tutorial 3: Displaying Data 

This tutorial shows you how to create a database in WebMatrix and how to display database data 
in a page when you use ASP.NET Web Pages (Razor). 

What you'll learn: 

β€’  How to use WebMatrix tools to create a database and database tables. 
β€’  How to use WebMatrix tools to add data to a database. 
β€’  How to display data from the database on a page. 
β€’  How to run SQL commands in ASP.NET Web Pages. 
β€’  How to customize the WebGrid helper to change the data display and to add paging and 

sorting. 

Features/technologies discussed: 

β€’  WebMatrix database tools. 
β€’ 

WebGrid helper. 

What You'll Build 

In the previous tutorial, you were introduced to ASP.NET Web Pages (.cshtml files), to the basics 
of Razor syntax, and to helpers. In this tutorial, you'll begin creating the actual web application 
that you'll use for the rest of the series. The app is a simple movie application that lets you view, 
add, change, and delete information about movies. 

When you're done with this tutorial, you'll be able to view a movie listing that looks like this page: 

But to begin, you have to create a database.  

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

39 

 
A Very Brief Introduction to Databases 

This tutorial will provide only the briefest introduction to databases. If you have database 
experience, you can skip this short section.  

A database contains one or more tables that contain information β€” for example, tables for 
customers, orders, and vendors,or for students, teachers, classes, and grades. Structurally, a 
database table is like a spreadsheet. Imagine a typical address book. For each entry in the address 
book (that is, for each person) you have several pieces of information such as first name, last 
name, address, email address, and phone number. 

(Rows are sometimes referred to as records, and columns are sometimes referred to as fields.) 

For most database tables, the table has to have a column that contains a unique value, like a 
customer number, account number, and so on. This value is known as the table's primary key, and 
you use it to identify each row in the table. In the example, the ID column is the primary key for 
the address book shown in the previous example. 

Much of the work you do in web applications consists of reading information out of the database 
and displaying it on a page. You'll also often gather information from users and add it to a 
database, or you'll modify records that are already in the database. (We'll cover all of these 
operations in the course of this tutorial set.) 

Database work can be enormously complex and can require specialized knowledge. For this 
tutorial set, though, you have to understand only basic concepts, which will all be explained as 
you go. 

Creating a Database 

WebMatrix includes tools that make it easy to create (or define) a database and to create tables in 
the database. For this tutorial set, you'll create a database that has only one table in it β€” Movies.  

Open WebMatrix if you haven't already done so, and open the WebPagesMovies site that you 
created in the previous tutorial.  

In the left pane, click the Database workspace.  

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

40 

 
The ribbon changes to show database-related tasks. In the ribbon, click New Database.  

WebMatrix creates a database (an .sdf file) that has the same name as your site β€” 
WebPagesMovies.sdf. (You won't do this here, but you can rename the file to anything you like, as 
long as it has an .sdf extension.)  

Creating a Table 

In the ribbon, click New Table. WebMatrix opens the table designer in a new tab. (If the New 
Table option isn't available, make sure that the new database is selected in the tree view on the 
left.) 

In the text box at the top (where the watermark says "Enter table name"), enter "Movies". 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

41 

 
 
 
The pane underneath the table name is where you define individual columns. For the Movies 
table in this tutorial, you'll create only a few columns: ID, Title, Genre, and Year.  

In the Name box, enter "ID". Entering a value here activates all the controls for the new column.  

Tab to the Data Type list and choose int. This value specifies that the ID column will contain 
integer (number) data. 

Note   We won't call it out any more here (much), but you can use standard Windows 
keyboard gestures to navigate in this grid. For example, you can tab between fields, you 
can just start typing in order to select an item in a list, and so on. 

Tab past the Default Value box (that is, leave it blank). Tab to the Is Primary Key check box and 
select it. This option tells the database that the ID column will contain the data that identifies 
individual rows. (That is, each row will have a unique value in the ID column that you can use to 
find that row.)  

Choose the Is Identity option. This option tells the database that it should automatically generate 
the next sequential number for each new row. (The Is Identity option works only if you've also 
selected the Is Primary Key option.)  

Click in the next grid row, or press Tab twice to finish the current row. Either gesture saves the 
current row and starts the next one. Notice that the Default Value column now says Null. (Null is 
the default value for the default value, so to speak.) 

When you've finished defining the new ID column, the designer will look like this illustration: 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

42 

 
To create the next column, click in the box in the Name column. Enter "Title" for the column and 
then select nvarchar for the Data Type value. The "var" part of nvarchar tells the database that 
the data for this column will be a string whose size might vary from record to record. (The "n" 
prefix represents "national," which indicates that the field can hold character data for any 
alphabet or writing system β€” that is, the field holds Unicode data.)   

When you choose nvarchar, another box appears where you can enter the maximum length for 
the field. Enter 50, on the assumption that no movie title that you'll work with in this tutorial will 
be longer than 50 characters.  

Skip Default Value and clear the Allow Nulls option. You don't want the database to allow any 
movies to be entered into the database that don't have a title. 

When you're done and move to the next row, the designer looks like this illustration: 

Repeat these steps to create a column named "Genre", except for the length, set it to just 30.  

Create another column named "Year." For the data type, choose nchar (not nvarchar) and set the 
length to 4. For the year, you're going to use a 4-digit number like "1995" or "2010", so you don't 
require a variable-sized column. 

Here's what the finished design looks like: 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

43 

 
 
 
Press Ctrl+S or click the Save button in the Quick Access toolbar. Close the database designer by 
closing the tab. 

Adding Some Example Data 

Later in this tutorial series you'll create a page where you can enter new movies in a form. For 
now, however, you can add some example data that you can then display on a page. 

In the Database workspace in WebMatrix, notice that there's a tree that shows you the .sdf file 
you created earlier. Open the node for your new .sdf file, and then open the Tables node. 

Right-click the Movies node and then choose Data. WebMatrix opens a grid where you can enter 
data for the Movies table: 

Click the Title column and enter "When Harry Met Sally". Move to the Genre column (you can use 
the Tab key) and enter "Romantic Comedy". Move to the Year column and enter "1989": 

Press Enter, and WebMatrix saves the new movie. Notice that the ID column has been filled in. 

Enter another movie (for example, "Gone with the Wind", "Drama", "1939"). The ID column is 
filled in again: 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

44 

 
 
 
 
Enter a third movie (for example, "Ghostbusters", "Comedy"). As an experiment, leave the Year 
column blank and then press Enter. Because you unselected the Allow Nulls option, the database 
shows an error: 

Click OK to go back and fix the entry (the year for "Ghostbusters" is 1984), and then press Enter.  

Fill in several movies until you have 8 or so. (Entering 8 makes it easier to work with paging later. 
But if that's too many, enter just a few for now.) The actual data doesn't matter.  

If you entered all the movies without any errors, the ID values are sequential. If you tried to save 
an incomplete movie record, the ID numbers might not be sequential. If so, that's okay. The 
numbers don't have any inherent meaning, and the only thing that's important is that they're 
unique in the Movies table. 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

45 

 
 
 
Close the tab that contains the database designer. 

Now you can turn to displaying this data on a web page. 

Adding the Web Data Package 

You access data in ASP.NET Web Pages sites using helpers that are available in the WebData 
package. Because you used the Empty Site template in WebMatrix to create your Movies site, the 
WebData package isn't automatically included. Therefore, you have to add the package to your 
site. 

In the left pane, click the Files workspace.  

In the ribbon, click the Gallery button. 

The NuGet Gallery is displayed. 

In the search box, enter "Microsoft.AspNet.WebPages.WebData" to narrow down the list of 
packages that are displayed. 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

46 

 
 
Select the Microsoft ASP.NET Web Pages 2 Web Data package and then click Install. 

The Gallery page displays details about the package.  

Click Install. After you accept the license, WebMatrix installs the Web Data package. 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

47 

 
 
Now you're ready to display data on a page. 

Displaying Data in a Page by Using the WebGrid Helper 

To display data in a page, you're going to use the WebGrid helper. This helper produces a display in 
a grid or table (rows and columns). As you'll see, you'll be able refine the grid with formatting and 
other features.  

To run the grid, you'll have to write a few lines of code. These few lines will serve as a kind of 
pattern for almost all of the data access that you do in this tutorial. 

Note   You actually have many options for displaying data on a page; the WebGrid helper is 
just one. We chose it for this tutorial because it's the easiest way to display data and 
because it's reasonably flexible. In the next tutorial set, you'll see how to use a more 
"manual" way to work with data in the page, which gives you more direct control over how 
to display the data. 

In the left pane in WebMatrix, click the Files workspace. In the tree view, select the root of the 
website. 

The new database you created is in the App_Data folder. If the folder didn't already exist, 
WebMatrix created it for your new database. (The folder might have existed if you'd previously 
installed helpers.)  

In the ribbon, click New. In the Choose a File Type box, choose CSHTML. 

In the Name box, name the new page "Movies.cshtml": 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

48 

Click the OK button. WebMatrix opens a new file with some skeleton elements in it. First you'll 
write some code to go get the data from the database. Then you'll add markup to the page to 
actually display the data. 

Writing the Data Query Code 

At the top of the page, between the @{ and } characters, enter the following code. (Make sure 
that you enter this code between the opening and closing braces.) 

var db = Database.Open("WebPagesMovies"); 
var selectedData = db.Query("SELECT * FROM Movies"); 
var grid = new WebGrid(source: selectedData); 

The first line opens the database that you created earlier, which is always the first step before 
doing something with the database. You tell the Database.Open method name of the database to 
open. Notice that you don't include .sdf in the name. The Open method assumes that it's looking 
for an .sdf file (that is, WebPagesMovies.sdf) and that the .sdf file is in the App_Data folder. 
(Earlier we noted that the App_Data folder is reserved; this scenario is one of the places where 
ASP.NET makes assumptions about that name.) 

When the database is opened, a reference to it is put into the variable named db. (Which could be 
named anything.) The db variable is how you'll end up interacting with the database. 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

49 

 
The second line actually fetches the database data by using the Query method. Notice how this 
code works: the db variable has a reference to the opened database, and you invoke the Query 
method by using the db variable (db.Query).  

Thequery itself is a SQL Select statement. (For a little background about SQL, see the explanation 
later.) In the statement, Movies identifies the table to query. The * character specifies that the 
query should return all the columns from the table. (You could also list columns individually, 
separated by commas.)  

The results of the query, if any, are returned and made available in the selectedData variable. 
Again, the variable could be named anything. 

Finally, the third line tells ASP.NET that you want to use an instance of the WebGrid helper. You 
create (instantiate) the helper object by using the new keyword and pass it the query results via 
the selectedData variable. The new WebGrid object, along with the results of the database query, 
are made available in the grid variable. You'll need that result in a moment to actually display the 
data in the page. 

At this stage, the database has been opened, you've gotten the data you want, and you've 
prepared the WebGrid helper with that data. Next is to create the markup in the page. 

Structured Query Language (SQL) 

SQL is a language that's used in most relational databases for managing data in a database. It 
includes commands that let you retrieve data and update it, and that let you create, modify, and 
manage data in database tables. SQL is different than a programming language (like C#). With 
SQL, you tell the database what you want, and it's the database's job to figure out how to get the 
data or perform the task. Here are examples of some SQL commands and what they do: 

Select * From Movies 

SELECT ID, Name, Price FROM Product WHERE Price > 10.00 ORDER BY Name 

The first Select statement gets all the columns (specified by *) from the Movies table. 

The second Select statement fetches the ID, Name, and Price columns from records in the 
Product table whose Price column value is more than 10. The command returns the results in 
alphabetical order based on the values of the Name column. If no records match the price criteria, 
the command returns an empty set. 

INSERT INTO Product (Name, Description, Price) VALUES ('Croissant', 'A flaky delight', 
1.99) 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

50 

This command inserts a new record into the Product table, setting the Name column to 
"Croissant", the Description column to "A flaky delight", and the price to 1.99. 

Notice that when you're specifying a non-numeric value, the value is enclosed in single quotation 
marks (not double quotation marks, as in C#). You use these quotation marks around text or date 
values, but not around numbers. 

DELETE FROM Product WHERE ExpirationDate < '01/01/2008' 

This command deletes records in the Product table whose expiration date column is earlier than 
January 1, 2008. (The command assumes that the Product table has such a column, of course.) 
The date is entered here in MM/DD/YYYY format, but it should be entered in the format that's 
used for your locale. 

The Insert and Delete commands don’t return result sets. Instead, they return a number that 
tells you how many records were affected by the command. 

For some of these operations (like inserting and deleting records), the process that's requesting 
the operation has to have appropriate permissions in the database. That's why for production 
databases you often have to supply a user name and password when you connect to the 
database. 

There are dozens of SQL commands, but they all follow a pattern like the commands you see 
here. You can use SQL commands to create database tables, count the number of records in a 
table, calculate prices, and perform many more operations. 

Adding Markup to Display the Data 

Inside the <head> element, set contents of the <title> element to "Movies": 

<head> 
<meta charset="utf-8" /> 
<title>Movies</title> 
</head> 

Inside the <body> element of the page, add the following: 

<h1>Movies</h1> 
<div> 
    @grid.GetHtml() 
</div> 

That's it. The grid variable is the value you created when you created the WebGrid object in code 
earlier.  

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

51 

In the WebMatrix tree view, right-click the page and select Launch in browser.You'll see 
something like this page: 

(Remember that the URL that you see in the browser might use a different port number than 
what you see in these screenshots β€” instead of locahost:56011, you'll see localhost followed by a 
different number.) 

Click a column heading link to sort by that column. Being able to sort by clicking a heading is a 
feature that's built into the WebGrid helper. 

The GetHtml method, as its name suggests, generates markup that displays the data. By default, 
the GetHtml method generates an HTML <table> element. (If you want, you can verify the 
rendering by looking at the source of the page in the browser.) 

Modifying the Look of the Grid 

Using the WebGrid helper like you just did is easy, but the resulting display is plain. The WebGrid 
helper has all sorts of options that let you control how the data is displayed. There are far too 
many to explore in this tutorial, but this section will give you an idea of some of those options. A 
few additional options will be covered in later tutorials in this series. 

Specifying Individual Columns to Display 

To start, you can specify that you want to display only certain columns. By default, as you've seen, 
the grid shows all four of the columns from the Movies table. 

In the Movies.cshtml file, replace the @grid.GetHtml() markup that you just added with the 
following: 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

52 

 
 
 
@grid.GetHtml( 
    columns: grid.Columns( 
        grid.Column("Title"), 
        grid.Column("Genre"), 
        grid.Column("Year") 
    ) 
) 

To tell the helper which columns to display, you include a columns parameter for the GetHtml 
method and pass in a collection of columns. In the collection, you specify each column to include. 
You specify an individual column to display by including a grid.Column object, and pass in the 
name of the data column you want. (These columns must be included in the SQL query results β€” 
the WebGrid helper cannot display columns that were not returned by the query.) 

Launch the Movies.cshtml page in the browser again, and this time you get a display like the 
following one (notice that no ID column is displayed): 

Changing the Look of the Grid 

There are quite a few more options for displaying columns, some of which will be explored in later 
tutorials in this set. For now, this section will introduce you to ways in which you can style the grid 
as a whole. 

Inside the <head> section of the page, just before the closing </head> tag, add the following 
<style>element: 

<style type="text/css"> 
  .grid { margin: 4px; border-collapse: collapse; width: 600px; } 
  .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 
  .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 
  .alt { background-color: #E8E8E8; color: #000; } 
</style> 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

53 

 
This CSS markup defines classes named grid, head, and so on. You could also put these style 
definitions in a separate .css file and link that to the page. (In fact,you'll do that later in this 
tutorial set.) But to make things easy for this tutorial, they're inside the same page that displays 
the data. 

Now you can get the WebGrid helper to use these style classes. The helper has a number of 
properties (for example, tableStyle) for just this purpose β€” you assign a CSS style class name to 
them, and that class name is rendered as part of the markup that's rendered by the helper. 

Change the grid.GetHtml markup so that it now looks like this code: 

@grid.GetHtml( 
    tableStyle: "grid", 
    headerStyle: "head", 
    alternatingRowStyle: "alt", 
    columns: grid.Columns( 
        grid.Column("Title"), 
        grid.Column("Genre"), 
        grid.Column("Year") 
    ) 
) 

What's new here is that you've added tableStyle, headerStyle, and alternatingRowStyle 
parameters to the GetHtml method. These parameters have been set to the names of the CSS 
styles that you added a moment ago.  

Run the page, and this time you see a grid that looks much less plain than before: 

To see what the GetHtml method generated, you can look at the source of the page in the 
browser. We won't go into detail here, but the important point is that by specifying parameters 
like tableStyle, you caused the grid to generate HTML tags like the following: 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

54 

 
 <table class="grid"> 

The <table> tag has had a class attribute added to it that references one of the CSS rules that you 
added earlier. This code shows you the basic pattern β€” different parameters for the GetHtml 
method let you reference CSS classes that the method then generates along with the markup. 
What you do with the CSS classes is up to you. 

Adding Paging 

As the last task for this tutorial, you'll add paging to the grid. Right now it's no problem to display 
all your movies at once. But if you added hundreds of movies, the page display would get long.  

In the page code, change the line that creates the WebGrid object to the following code: 

var grid = new WebGrid(source: selectedData, rowsPerPage: 3); 

The only difference from before is that you've added a rowsPerPage parameter that's set to 3.  

Run the page. The grid displays 3 rows at a time, plus navigation links that let you page through 
the movies in your database: 

Coming Up Next 

In the next tutorial, you'll learn how to use Razor and C# code to get user input in a form. You'll 
add a search box to the Movies page so that you can find movies by title or genre. 

Additional Resources 

β€’  Complete Listing for Movies Page 
β€’ 

Introduction to ASP.NET Web Programming Using the Razor Syntax 

Introducing ASP.NET Web Pages 2 

Tutorial 3: Displaying Data 

55 

 
 
 
Tutorial 4: HTML Form Basics 

This tutorial shows you the basics of how to create an input form and how to handle the user's 
input when you use ASP.NET Web Pages (Razor). And now that you've got a database, you'll use 
your form skills to let users find specific movies in the database. 

What you'll learn: 

β€’  How to create a form by using standard HTML elements. 
β€’  How to read the user's input in a form. 
β€’  How to create a SQL query that selectively gets data by using a search term that the user 

supplies. 

β€’  How to have fields in the page "remember" what the user entered. 

Features/technologies discussed: 

β€’  The Request object. 
β€’  The SQL Where clause. 

What You'll Build 

In the previous tutorial, you created a database, added data to it, and then used the WebGrid 
helper to display the data. In this tutorial,you'll add a search box that lets you find movies of a 
specific genre or whose title contains whatever word you enter. (For example, you'll be able to 
find all movies whose genre is "Action" or whose title contains "Harry" or "Adventure.") 

When you're done with this tutorial, you'll have a page like this one: 

The listing part of the page is the same as in the last tutorial β€” a grid. The difference will be that 
the grid will show only the movies that you searched for. 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

56 

 
About HTML Forms 

(If you've got experience with creating HTML forms and with the difference between GET and 
POST, you can skip this section.)  

A form has user input elements β€” text boxes, buttons, radio buttons, check boxes, drop-down 
lists, and so on. Users fill in these controls or make selections and then submit the form by clicking 
a button.  

The basic HTML syntax of a form is illustrated by this example: 

<form method="post"> 
<input type="text" name="name" value="" /> 
<br/> 
<input type="submit" name="submit" value="Submit" /> 
</form> 

When this markup runs in a page, it creates a simple form that looks like this illustration: 

The <form> element encloses HTML elements to be submitted. (An easy mistake to make is to add 
elements to the page but then forget to put them inside a <form> element. In that case, nothing is 
submitted.) The method attribute tells the browser how to submit the user input. You set this to 
post if you're performing an update on the server or to get if you're just fetching data from the 
server.  

GET, POST, and HTTP Verb Safety 

HTTP, the protocol that browsers and servers use to exchange information, is remarkably simple 
in its basic operations. Browsers use only a few verbs to make requests to servers. When you 
write code for the web, it's helpful to understand these verbs and how the browser and server 
use them. Far and away the most commonly used verbs are these: 

GET. The browser uses this verb to fetch something from the server. For example, when you type a 
URL into your browser, the browser performs a GET operation to request the page you want. If the 
page includes graphics, the browser performs additional GET operations to get the images. If the 
GET operation has to pass information to the server, the information is passed as part of the URL 
in the query string. 

POST. The browser sends a POST request in order to submit data to be added or changed on the 
server. For example, the POST verb is used to create records in a database or change existing ones. 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

57 

 
Most of the time, when you fill in a form and click the submit button, the browser performs a POST 
operation. In a POST operation, the data being passed to the server is in the body of the page. 

An important distinction between these verbs is that a GET operation is not supposed to change 
anything on the server β€” or to put it in a slightly more abstract way, a GET operation does not 
result in a change in state on the server. You can perform a GET operation on the same resources 
as many times as you like, and those resources don't change. (A GET operation is often said to be 
"safe," or to use a technical term, is idempotent.) In contrast, of course, a POST request changes 
something on the server each time you perform the operation. 

Two examples will help illustrate this distinction. When you perform a search using an engine like 
Bing or Google, you fill in a form that consists of one text box, and then you click the search 
button. The browser performs a GET operation, with the value you entered into the box passed as 
part of the URL. Using a GET operation for this type of form is fine, because a search operation 
doesn't change any resources on the server, it just fetches information. 

Now consider the process of ordering something online. You fill in the order details and then click 
the submit button. This operation will be a POST request, because the operation will result in 
changes on the server, such as a new order record, a change in your account information, and 
perhaps many other changes. Unlike the GET operation, you cannot repeat your POST request β€” if 
you did, each time you resubmitted the request, you'd generate a new order on the server. (In 
cases like this, websites will often warn you not to click a submit button more than once, or will 
disable the submit button so that you don't resubmit the form accidentally.)  

In the course of this tutorial, you'll use both a GET operation and a POST operation to work with 
HTML forms. We'll explain in each case why the verb you use is the appropriate one. 

(To learn more about HTTP verbs, see the Method Definitions article on the W3C site.) 

Most user input elements are HTML <input> elements. They look like <input type="type" 
name="name">, where type indicates the kind of user input control you want. These elements are 
the common ones: 

β€’  Text box: <input type="text"> 
β€’  Check box: <input type="check"> 
β€’  Radio button: <input type="radio"> 
β€’  Button: <input type="button"> 
β€’ 

Submit button: <input type="submit"> 

You can also use the <textarea> element to create a multiline text box and the <select> element 
to create a drop-down list or scrollable list. (For more about HTML form elements, see HTML 
Forms and Input on the W3Schools site.)  

The name attribute is very important, because the name is how you'll get the value of the element 
later, as you'll see shortly. 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

58 

The interesting part is what you, the page developer, do with the user's input. There's no built-in 
behavior associated with these elements. Instead, you have to get the values that the user has 
entered or selected and do something with them. That's what you'll learn in this tutorial. 

HTML5 and Input Forms 

As you might know, HTML is in transition and the latest version (HTML5) includes support for 
more intuitive ways for users to enter information. For example, in HTML5, you (the page 
developer) can tell the page that you want the user to enter a date. The browser can then 
automatically display a calendar rather than requiring the user to enter a date manually. 
However, HTML5 is new and is not supported in all browsers yet. 

ASP.NET Web Pages supports HTML5 input to the extent that the user's browser does. For an idea 
of the new attributes for the <input> element in HTML5, see HTML <input> type Attribute on the 
W3Schools site. 

Creating the Form 

In WebMatrix, in the Files workspace, open the Movies.cshtml page.  

After the closing </h1> tag and before the opening <div> tag of the grid.GetHtml call, add the 
following markup: 

<form method="get"> 
<div> 
<label for="searchGenre">Genre to look for:</label> 
<input type="text" name="searchGenre" value="" /> 
<input type="Submit" value="Search Genre" /><br/> 
    (Leave blank to list all movies.)<br/> 
</div> 
</form> 

This markup creates a form that has a text box named searchGenre and a submit button. The text 
box and submit button are enclosed in a <form> element whose method attribute is set to get. 
(Remember that if you don't put the text box and submit button inside a <form> element, nothing 
will be submitted when you click the button.) You use the GET verb here because you're creating a 
form that does not make any changes on the server β€” it just results in a search. (In the previous 
tutorial, you used a post method, which is how you submit changes to the server. You'll see that 
in the next tutorial again.) 

Run the page. Although you haven't defined any behavior for the form, you can see what it looks 
like: 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

59 

Enter a value into the text box, like "Comedy." Then click Search Genre. 

Take note of the URL of the page. Because you set the <form> element's method attribute to get, 
the value you entered is now part of the query string in the URL, like this: 

http://localhost:45661/Movies.cshtml?searchGenre=Comedy 

Reading Form Values 

The page already contains some code that gets database data and displays the results in a grid. 
Now you have to add some code that reads the value of the text box so you can run a SQL query 
that includes the search term.  

Because you set the form's method to get, you can read the value that was entered into the text 
box by using code like the following: 

var searchTerm = Request.QueryString["searchGenre"]; 

The Request.QueryString object (the QueryString property of the Request object) includes the 
values of elements that were submitted as part of the GET operation. The Request.QueryString 
property contains a collection (a list) of the values that are submitted in the form. To get any 
individual value, you specify the name of the element that you want. That's why you have to have 
a name attribute on the <input> element (searchTerm) that creates the text box. (For more about 
the Request object, see the sidebar later.)  

It's simple enough to read the value of the text box. But if the user didn't enter anything at all in 
the text box but clicked Search anyway, you can ignore that click, since there's nothing to search.  

The following code is an example that shows how to implement these conditions. (You don't have 
to add this code yet; you'll do that in a moment.) 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

60 

 
 
if(!Request.QueryString["searchGenre"].IsEmpty() ) {  
     // Do something here 
} 

The test breaks down in this way: 

β€’  Get the value of Request.QueryString["searchGenre"], namely the value that was entered 

β€’ 

into the <input> element named searchGenre. 
Find out if it's empty by using the IsEmpty method.This method is the standard way to 
determine whether something (for example, a form element) contains a value. But really, 
you care only if it's not empty, therefore ...  

β€’  Add the ! operator in front of the IsEmpty test. (The ! operator means logical NOT). 

In plain English, the entire if condition translates into the following: If the form's searchGenre 
element is not empty, then ...  

This block sets the stage for creating a query that uses the search term. You'll do that in the next 
section. 

The Request Object 

The Request object contains all the information that the browser sends to your application when a 
page is requested or submitted. This object includes any information that the user provides, like 
text box values or a file to upload. It also includes all sorts of additional information, like cookies, 
values in the URL query string (if any), the file path of the page that is running, the type of 
browser that the user is using, the list of languages that are set in the browser, and much more. 

The Request object is a collection (list) of values. You get an individual value out of the collection 
by specifying its name: 

var someValue = Request["name"]; 

The Request object actually exposes several subsets. For example: 

Request.Form gives you values from elements inside the submitted <form> element if the request 
is a POST request. 

Request.QueryString gives you just the values in the URL's query string. (In a URL like 
http://mysite/myapp/page?searchGenre=action&page=2, the ?searchGenre=action&page=2 section 
of the URL is the query string.) 

Request.Cookies collection gives you access to cookies that the browser has sent.  

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

61 

To get a value that you know is in the submitted form, you can use Request["name"]. 
Alternatively, you can use the more specific versions Request.Form["name"] (for POST requests) or 
Request.QueryString["name"] (for GET requests). Of course, name is the name of the item to get.  

The name of the item you want to get has to be unique within the collection you're using. That's 
why the Request object provides the subsets like Request.Form and Request.QueryString. Suppose 
that your page contains a form element named userName and also contains a cookie named 
userName. If you get Request["userName"], it's ambiguous whether you want the form value or the 
cookie. However, if you get Request.Form["userName"] or Request.Cookie["userName"], you're 
being explicit about which value to get. 

It's a good practice to be specific and use the subset of Request that you're interested in, like 
Request.Form or Request.QueryString. For the simple pages that you're creating in this tutorial, it 
probably doesn't really make any difference. However, as you create more complex pages, using 
the explicit version Request.Form or Request.QueryString can help you avoid problems that can 
arise when the page contains a form (or multiple forms), cookies, query string values, and so on. 

Creating a Query by Using a Search Term 

Now that you know how to get the search term that the user entered, you can create a query that 
uses it. Remember that to get all the movie items out of the database, you're using a SQL query 
that looks like this statement: 

SELECT * FROM Movies 

To get only certain movies, you have to use a query that includes a Where clause. This clause lets 
you set a condition on which rows are returned by the query. Here's an example: 

SELECT * FROM Movies WHERE Genre = 'Action' 

The basic format is WHERE column = value. You can use different operators besides just =, like > 
(greater than), < (less than), <> (not equal to), <= (less than or equal to), etc., depending on what 
you're looking for. 

In case you're wondering, SQL statements are not case sensitive β€” SELECT is the same as Select 
(or even select). However, people often capitalize keywords in a SQL statement, like SELECT and 
WHERE, to make it easier to read. 

Passing the search term as a parameter 

Searching for a specific genre is easy enough (WHERE Genre = 'Action'), but you want to be able 
to search for any genre that the user enters. To do that, you create as SQL query that includes a 
placeholder for the value to search. It will look like this command: 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

62 

SELECT * FROM Movies WHERE Genre = @0 

The placeholder is the @ character followed by zero. As you might guess, a query can contain 
multiple placeholders, and they'd be named @0, @1, @2, etc.  

To set up the query and actually pass it the value, you use the code like the following: 

selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 
selectedData = db.Query(selectCommand, Request.QueryString["searchGenre"]); 

This code is similar to what you've already done to display data in the grid. The only differences 
are: 

β€’  The query contains a placeholder (WHERE Genre = @0"). 
β€’  The query is put into a variable (selectCommand); before, you passed the query directly to 

the db.Query method.  

β€’  When you call the db.Query method, you pass both the query and the value to use for the 
placeholder. (If the query had multiple placeholders, you'd pass them all as separate 
values to the method.) 

If you put all these elements together, you get the following code: 

if(!Request.QueryString["searchGenre"].IsEmpty() ) {  
    searchTerm = Request.QueryString["searchGenre"]; 
    selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 
    selectedData = db.Query(selectCommand, searchTerm); 
} 

Important!   Using placeholders (like @0) to pass values to a SQL command is extremely 
important for security. The way you see it here, with placeholders for variable data, is the 
only way you should construct SQL commands.  

Never construct a SQL statement by putting together (concatenating) literal text and 
values you get from the user. Concatenating user input into a SQL statement opens your 
site to a SQL injection attack where a malicious user submits values to your page that hack 
your database. (You can read more in the article SQL Injection the MSDN website.)  

Updating the Movies Page with Search Code 

Now you can update the code in the Movies.cshtml file. To begin, replace the code in the code 
block at the top of the page with this code: 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

63 

 
 
var db = Database.Open("WebPagesMovies"); 
var selectCommand = "SELECT * FROM Movies"; 
var searchTerm = ""; 

The difference here is that you've put the query into the selectCommand variable, which you'll pass 
to db.Query later. Putting the SQL statement into a variable lets you change the statement, which 
is what you'll do to perform the search. 

You've also removed these two lines, which you'll put back in later: 

var selectedData = db.Query("SELECT * FROM Movies"); 
var grid = new WebGrid(source: selectedData, rowsPerPage: 3); 

You don't want to run the query yet (that is, call db.Query) and you don't want to initialize the 
WebGrid helper yet either. You'll do those things after you've figured out which SQL statement has 
to run.  

After this rewritten block, you can add the new logic for handling the search. The completed code 
will look like the following. Update the code in your page so it matches this example: 

@{ 
    var db = Database.Open("WebPagesMovies") ; 
    var selectCommand = "SELECT * FROM Movies"; 
    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  
        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 
        searchTerm = Request.QueryString["searchGenre"]; 
    } 

    var selectedData = db.Query(selectCommand, searchTerm); 
    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  
rowsPerPage:3); 
} 

The page now works like this. Every time the page runs, the code opens the database and the 
selectCommand variable is set to the SQL statement that gets all the records from the Movies table. 
The code also initializes the searchTerm variable. 

However, if the current request includes a value for the searchGenre element, the code sets 
selectCommand to a different query β€” namely, to one that includes the Where clause to search for a 
genre. It also sets searchTerm to whatever was passed for the search box (which might be 
nothing). 

Regardless of which SQL statement is in selectCommand, the code then calls db.Query to run the 
query, passing it whatever is in searchTerm. If there's nothing in searchTerm, it doesn't matter, 
because in that case there's no parameter to pass the value to selectCommand anyway. 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

64 

 
 
Finally, the code initializes the WebGrid helper by using the query results, just like before. 

You can see that by putting the SQL statement and the search term into variables, you've added 
flexibility to the code. As you'll see later in this tutorial, you can use this basic framework and 
keep adding logic for different types of searches.  

Testing the Search-by-Genre Feature 

In WebMatrix, run the Movies.cshtml page. You see the page with the text box for genre. 

Enter a genre that you've entered for one of your test records, then click Search. This time you 
see a listing of just the movies that match that genre: 

Enter a different genre and search again. Try entering the genre by using all lowercase or all 
uppercase letters so that you can see that the search is not case sensitive.  

"Remembering" What the User Entered 

You might have noticed that after you entered a genre and clicked Search Genre, you saw a listing 
for that genre. However, the search text box was empty β€” in other words, it didn't remember 
what you'd entered. 

It's important to understand why this behavior occurs. When you submit a page, the browser 
sends a request to the web server. When ASP.NET gets the request, it creates a brand-new 
instance of the page, runs the code in it, and then renders the page to the browser again. In 
effect, though, the page doesn't know that you were just working with a previous version of itself. 
All it knows is that it got a request that had some form data in it. 

Every time you request a page β€” whether for the first time or by submitting it β€” you're getting a 
new page. The web server has no memory of your last request. Neither does ASP.NET, and neither 
does the browser. The only connection between these separate instances of the page is any data 
that you transmit between them. If you submit a page, for example, the new page instance can 
get the form data that was sent by the earlier instance. (Another way to pass data between pages 
is to use cookies.)  

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

65 

 
A formal way to describe this situation is to say that web pages are stateless. Web servers and the 
pages themselves and the elements in the page do not maintain any information about the 
previous state of a page. The web was designed this way because maintaining state for individual 
requests would quickly exhaust the resources of web servers, which often handle thousands, 
maybe even hundreds of thousands, of requests per second.   

So that's why the text box was empty. After you submitted the page, ASP.NET created a new 
instance of the page and ran through the code and markup. There was nothing in that code that 
told ASP.NET to put a value into the text box. So ASP.NET didn't do anything, and the text box was 
rendered without a value in it. 

There's actually an easy way to get around this issue. The genre that you entered into the text box 
is available to you in code β€” it's in Request.QueryString["searchGenre"].  

Update the markup for the text box so that the value attribute gets its value from searchTerm, like 
this example: 

<input type="text" name="searchGenre" value="@Request.QueryString["searchGenre"]" 
/> 

In this page, you could have also set the value attribute to the searchTerm variable, since that 
variable also contains the genre you entered. But using the Request object to set the value 
attribute as shown here is the standard way to accomplish this task. (Assuming you even want to 
do this β€” in some situations, you might want to render the page without values in the fields. It all 
depends on what's going on with your app.) 

Note   You can't "remember" the value of a text box that's used for passwords. It would be 
a security hole to allow people to fill in a password field by using code. 

Run the page again, enter a genre, and click Search Genre. This time not only do you see the 
results of the search, but the text box remembers what you entered last time: 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

66 

 
Searching for Any Word in the Title 

You can now search for any genre, but you might also want to search for a title. It's hard to get a 
title exactly right when you search, so instead you can search for a word that appears anywhere 
inside a title. To do that in SQL, you use the LIKE operator and syntax like the following: 

SELECT * FROM Movies WHERE Title LIKE '%adventure%' 

This command gets all the movies whose titles contain "adventure". When you use the LIKE 
operator, you include the wildcard character % as part of the search term. The search LIKE 
'adventure%' means "starting with 'adventure'". (Technically, it means "The string 'adventure' 
followed by anything.") Similarly, the search term LIKE '%adventure' means "anything followed 
by the string 'adventure'", which is another way to say "ending with 'adventure'". 

The search term LIKE '%adventure%' therefore means "with 'adventure' anywhere in the title." 
(Technically, "anything in the title, followed by 'adventure', followed by anything.") 

Inside the <form> element, add the following markup right under the closing </div> tag for the 
genre search (just before the closing </form> element): 

<div> 
<label for="SearchTitle">Movie title contains the following:</label> 
<input type="text" name="searchTitle"  
value="@Request.QueryString["searchTitle"]" /> 
<input type="Submit" value="Search Title" /><br/> 
</div> 

The code to handle this search is similar to the code for the genre search, except that you have to 
assemble the LIKE search. Inside the code block at the top of the page, add this if block just after 
the if block for the genre search: 

if(!Request.QueryString["searchTitle"].IsEmpty() ) {  
    selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 
    searchTerm = "%" + Request["searchTitle"] + "%";  
} 

This code uses the same logic you saw earlier, except that the search uses a LIKE operator and the 
code puts "%" before and after the search term.  

Notice how it was easy to add another search to the page. All you had to do was: 

β€’  Create an if block that tested to see whether the relevant search box had a value. 
β€’ 
β€’ 

Set the selectCommand variable to a new SQL statement. 
Set the searchTerm variable to the value to pass to the query. 

Here's the complete code block, which contains the new logic for a title search: 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

67 

@{ 
    var db = Database.Open("WebPagesMovies") ; 
    var selectCommand = "SELECT * FROM Movies"; 
    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  
        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 
        searchTerm = Request.QueryString["searchGenre"]; 
    } 

   if(!Request.QueryString["searchTitle"].IsEmpty() ) {  
        selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 
        searchTerm = "%" + Request["searchTitle"] + "%";  
    } 

    var selectedData = db.Query(selectCommand, searchTerm); 
    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  
rowsPerPage:8); 
} 

Here's a summary of what this code does: 

β€’  The variables searchTerm and selectCommand are initialized at the top. You're going to set 
these variables to the appropriate search term (if any) and appropriate SQL command 
based on what the user does in the page. The default search is the simple case of getting 
all the movies from the database. 
In the tests for searchGenre and searchTitle, the code sets searchTerm to the value you 
want to search for. Those code blocks also set selectCommand to an appropriate SQL 
command for that search. 

β€’ 

β€’  The db.Query method is invoked only once, using whatever SQL command is in 

selectedCommand and whatever value is in searchTerm. If there is no search term (no genre 
and no title word), the value of searchTerm is an empty string. However, that doesn't 
matter, because in that case the query doesn't require a parameter. 

Testing the Title Search Feature 

Now you can test your completed search page. Run Movies.cshtml. 

Enter a genre and click Search Genre. The grid displays movies of that genre, like before. 

Enter a title word and click Search Title. The grid displays movies that have that word in the title. 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

68 

 
 
 
Leave both text boxes blank and click either button. The grid displays all the movies. 

Combining the Queries 

You might notice that the searches you can perform are exclusive. You can't search the title and 
the genre at the same time, even if both search boxes have values in them. For example, you can't 
search for all action movies whose title contains "Adventure". (As the page is coded now, if you 
enter values for both genre and title, the title search gets precedence.) To create a search that 
combines the conditions,you would have to create a SQL query that has syntax like the following: 

SELECT * FROM Movies WHERE Genre = @0 AND Title LIKE @1 

And you'd have to run the query by using a statement like the following (roughly speaking): 

var selectedData = db.Query(selectCommand, searchGenre, searchTitle); 

Creating logic to allow many permutations of search criteria can get a bit involved, as you can see. 
Therefore, we'll stop here. 

Coming Up Next 

In the next tutorial, you'll create a page that uses a form to let users add movies to the database. 

Additional Resources 

Introduction to ASP.NET Web Programming Using the Razor Syntax 
β€’ 
SQL WHERE Clause on the W3Schools site 
β€’ 
β€’  Method Definitions article on the W3C site 

Introducing ASP.NET Web Pages 2 

Tutorial 4: HTML Form Basics 

69 

 
 
Tutorial 5: Entering Database Data by Using Forms 

This tutorial shows you how to create an entry form and then enter the data that you get from 
the form into a database table when you use ASP.NET Web Pages (Razor).  

What you'll learn: 

β€’  More about how to process entry forms. 
β€’  How to add (insert) data in a database. 
β€’  How to make sure that users have entered a required value in a form (how to validate 

user input). 

β€’  How to display validation errors. 
β€’  How to jump to another page from the current page. 

Features/technologies discussed: 

β€’  The Database.Execute method. 
β€’  The SQL Insert Into statement 
β€’  The Validation helper. 
β€’  The Response.Redirect method. 

What You'll Build 

In the tutorial earlier that showed you how to create a database, you entered database data by 
editing the database directly in WebMatrix, working in the Database workspace. In most apps, 
that's not a practical way to put data into the database, though. So in this tutorial, you'll create a 
web-based interface that lets you or anyone enter data and save it to the database. 

You'll create a page where you can enter new movies. The page will contain an entry form that 
has fields (text boxes) where you can enter a movie title, genre, and year.The page will look like 
this page: 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

70 

 
The text boxes will be HTML <input> elements that will look like this markup: 

<input type="text" name="genre" value="" /> 

Creating the Basic Entry Form 

Create a page named AddMovie.cshtml. 

Replace what's in the file with the following markup. Overwrite everything; you'll add a code 
block at the top shortly. 

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Add a Movie</title> 
</head> 
<body> 
<h1>Add a Movie</h1> 
<form method="post"> 
<fieldset> 
<legend>Movie Information</legend> 
<p><label for="title">Title:</label> 
<input type="text" name="title" value="@Request.Form["title"]" /> 

<p><label for="genre">Genre:</label> 
<input type="text" name="genre" value="@Request.Form["genre"]" /> 

<p><label for="year">Year:</label> 
<input type="text" name="year" value="@Request.Form["year"]" /> 

<p><input type="submit" name="buttonSubmit" value="Add Movie" /></p> 
</fieldset> 
</form> 
</body> 
</html> 

This example shows is typical HTML for creating a form. It uses <input> elements for the text 
boxes and for the submit button. The captions for the text boxes are created by using standard 
<label> elements. The <fieldset> and <legend> elements put a nice box around the form. 

Notice that in this page, the <form> element uses post as the value for the method attribute. In the 
previous tutorial, you created a form that used the get method. That was correct, because 
although the form submitted values to the server, the request did not make any changes. All it did 
was fetch data in different ways. However, in this page you will make changesβ€”you're going to 
add new database records. Therefore, this form should use the post method. (For more about the 
difference between GET and POST operations, see the GET, POST, and HTTP Verb Safety sidebar in 
the previous tutorial.) 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

71 

 
 
 
Note that each text box has a name element (title, genre, year). As you saw in the previous 
tutorial, these names are important because you must have those names so you can get the 
user's input later. You can use any names. It's helpful to use meaningful names that help you 
remember what data you're working with.  

The value attribute of each <input> element contains a bit of Razor code (for example, 
Request.Form["title"]). You learned a version of this trick in the previous tutorial to preserve the 
value entered into the text box (if any) after the form has been submitted. 

Getting the Form Values 

Next, you add code that processes the form. In outline, you'll do the following: 

1.  Check whether the page is being posted (was submitted). You want to your code to run 

only when users have clicked the button, not when the page first runs. 

2.  Get the values that the user entered into the text boxes. In this case, because the form is 

using the POST verb, you get the form values from the Request.Form collection. 
Insert the values as a new record in the Movies database table. 

3. 

At the top of the file, add the following code: 

@{ 
    var title = ""; 
    var genre = ""; 
    var year = ""; 

    if(IsPost){ 
        title = Request.Form["title"]; 
        genre = Request.Form["genre"]; 
        year = Request.Form["year"]; 
    } 
} 

The first few lines create variables (title, genre, and year) to hold the values from the text 
boxes.The line if(IsPost) makes sure that the variables are set only when users click the Add 
Movie button β€” that is, when the form has been posted. 

As you saw in an earlier tutorial, you get the value of a text box by using an expression like 
Request.Form["name"], where name is the name of the <input> element. 

The names of the variables (title, genre, and year) are arbitrary. Like the names that you assign 
to <input> elements, you can call them anything you like. (The names of the variables don't have 
to match the name attributes of <input> elements on the form.) But as with the <input> 
elements, it's a good idea to use variable names that reflect the data that they contain. When you 
write code, consistent names make it easier for you to remember what data you're working with. 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

72 

 
Adding Data to the Database 

In the code block you just added, just inside the closing brace ( } ) of the if block (not just inside 
the code block), add the following code: 

var db = Database.Open("WebPagesMovies"); 
var insertCommand = "INSERT INTO Movies (Title, Genre, Year) VALUES(@0, @1, @2)"; 
db.Execute(insertCommand, title, genre, year); 

This example is similar to the code you used in a previous tutorial to fetch and display data. The 
line that starts with db = opens the database, like before, and the next line defines a SQL 
statement, again as you saw before. However, this time it defines a SQL Insert Into statement. 
The following example shows the general syntax of the Insert Into statement: 

INSERT INTO table (column1, column2, column3, ...) VALUES (value1, value2, 
value3, ...) 

In other words, you specify the table to insert into, then list the columns to insert into, and then 
list the values to insert.(As noted before, SQL is not case sensitive but some people capitalize the 
keywords to make it easier to read the command.) 

The columns that you're inserting into are already listed in the command β€” (Title, Genre, 
Year). The interesting part is how you get the values from the text boxes into the VALUES part of 
the command. Instead of actual values, you see @0, @1, and @2, which are of course placeholders. 
When you run the command (on the db.Execute line), you pass the values that you got from the 
text boxes. 

Important!Remember that the only way you should ever include data entered online by a 
user in  a  SQL statement  is  to  use placeholders, as you see here  (VALUES(@0,  @1,  @2)). If 
you  concatenate  user  input  into  a  SQL  statement,  you  open  yourself  to  a  SQL  injection 
attack, as explained in HTML Form Basics (the previous tutorial). 

Still inside the if block, add the following line after the db.Execute line: 

Response.Redirect("~/Movies"); 

After the new movie has been inserted into the database, this line jumps you (redirects) to the 
Movies page so you can see the movie you just entered. The ~ operator means "root of the 
website." (The ~ operator works only in ASP.NET pages, not in HTML generally.) 

The complete code block looks like this example: 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

73 

 
@{ 
    var title = ""; 
    var genre = ""; 
    var year = ""; 

    if(IsPost){ 
        title = Request.Form["title"]; 
        genre = Request.Form["genre"]; 
        year = Request.Form["year"]; 

        var db = Database.Open("WebPagesMovies"); 
        var insertCommand = "INSERT INTO Movies (Title, Genre, Year) " + 
"Values(@0, @1, @2)"; 
        db.Execute(insertCommand, title, genre, year); 
        Response.Redirect("~/Movies"); 
    } 
} 

Testing the Insert Command (So Far) 

You're not done yet, but now is a good time to test.  

In the tree view of files in WebMatrix, right-click the AddMovie.cshtml page and then click Launch 
in browser. 

(If you end up with a different page in the browser, make sure that the URL is 
http://localhost:nnnnn/AddMovie), where nnnnn is the port number that you're using.) 

Did you get an error page? If so, read it carefully and make sure that the code looks exactly what 
was listed earlier. 

Enter a movie in the form β€” for example, use "Citizen Kane", "Drama", and "1941".(Or whatever.) 
Then click Add Movie. 

If all goes well, you're redirected to the Movies page. Make sure that your new movie is listed.  

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

74 

 
 
 
Validating User Input 

Go back to the AddMovie page, or run it again. Enter another movie, but this time, enter only the 
title β€” for example, enter "Singin' in the Rain". Then click Add Movie.  

You're redirected to the Movies page again. You can find the new movie, but it's incomplete. 

When you created the Movies table, you explicitly said that none of the fields could be null. Here 
you have an entry form for new movies, and you're leaving fields blank. That's an error.  

In this case, the database didn't actually raise (or throw) an error. You didn't supply a genre or 
year, so the code in the AddMovie page treated those values as so-called empty strings. When the 
SQL Insert Into command ran, the genre and year fields didn't have useful data in them, but 
they weren't null.  

Obviously, you don't want to let users enter half-empty movie information into the database. The 
solution is to validate the user's input. Initially, the validation will simply make sure that the user 
has entered a value for all of the fields (that is, that none of them contains an empty string). 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

75 

 
 
Null and Empty Strings 

In programming, there's a distinction between different notions of "no value." In general, a value 
is null if it has never been set or initialized in any way. In contrast, a variable that expects 
character data (strings) can be set to an empty string. In that case, the value is not null; it's just 
been explicitly set to a string of characters whose length is zero. These two statements show the 
difference: 

var firstName;       // Not set, so its value is null 

var firstName = "";  // Explicitly set to an empty string -- not null 

It's a little more complicated than that, but the important point is that null represents a sort of 
undetermined state. 

Now and then it's important to understand exactly when a value is null and when it's just an 
empty string. In the code for the AddMovie page, you get the values of the text boxes by using 
Request.Form["title"] and so on. When the page first runs (before you click the button), the 
value of Request.Form["title"] is null. But when you submit the form, Request.Form["title"] 
gets the value of the title text box. It's not obvious, but an empty text box is not null; it just has 
an empty string in it. So when the code runs in response to the button click, 
Request.Form["title"] has an empty string in it. 

Why is this distinction important? When you created the Movies table, you explicitly said that 
none of the fields could be null. But here you have an entry form for new movies, and you're 
leaving fields blank. You would reasonably expect the database to complain when you tried to 
save new movies that didn't have values for genre or year. But that's the point β€” even if you 
leave those text boxes blank, the values aren't null; they're empty strings. As a result, you're able 
to save new movies to the database with these columns empty β€” but not null! β€” values. 
Therefore, you have to make sure that users don't submit an empty string, which you can do by 
validating the user's input.  

The Validation Helper 

ASP.NET Web Pages includes a helper β€” the Validation helper β€” that you can use to make sure 
that users enter data that meets your requirements. The Validation helper is one of the helpers 
that's built in to ASP.NET Web Pages, so you don't have to install it as a package by using NuGet, 
the way you installed the Twitter helper in an earlier tutorial. 

To validate the user's input, you'll do the following: 

β€’  Use code to specify that you want to require values in the text boxes on the page.  
β€’  Put a test into the code so that the movie information is added to the database only if 

everything validates properly. 

β€’  Add code into the markup to display error messages. 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

76 

In the code block in the AddMovie page, right up at the top before the variable declarations, add 
the following code: 

Validation.RequireField("title", "You must enter a title"); 
Validation.RequireField("genre", "Genre is required"); 
Validation.RequireField("year", "You haven't entered a year"); 

You call Validation.RequireField once for each field (<input> element) where you want to 
require an entry.You can also add a custom error message for each call, like you see here. (We 
varied the messages just to show that you can put anything you like there.)  

If there's a problem, you want to prevent the new movie information from being inserted into the 
database. In the if(IsPost) block, use && (logical AND) to add another condition that tests 
Validation.IsValid(). When you're done, the whole if(IsPost) block looks like this code: 

if(IsPost && Validation.IsValid()){ 
    title = Request.Form["title"]; 
    genre = Request.Form["genre"]; 
    year = Request.Form["year"]; 

    var db = Database.Open("WebPagesMovies"); 
    var insertCommand = "INSERT INTO Movies (Title, Genre, Year)" +  
        " Values(@0, @1, @2)"; 
    db.Execute(insertCommand, title, genre, year); 
    Response.Redirect("~/Movies"); 
} 

If there's a validation error with any of the fields that you registered by using the Validation 
helper, the Validation.IsValid method returns false. And in that case, none of the code in that 
block will run, so no invalid movie entries will be inserted into the database. And of course you're 
not redirected to the Movies page. 

The complete code block, including the validation code, now looks like this example: 

@{ 
    Validation.RequireField("title", "You must enter a title"); 
    Validation.RequireField("genre", "Genre is required"); 
    Validation.RequireField("year", "You haven't entered a year"); 

    var title = ""; 
    var genre = ""; 
    var year = ""; 

    if(IsPost && Validation.IsValid()){ 
       title = Request.Form["title"]; 
       genre = Request.Form["genre"]; 
       year = Request.Form["year"]; 

       var db = Database.Open("WebPagesMovies"); 
       var insertCommand = "INSERT INTO Movies (Title, Genre, Year) " +  
            " Values(@0, @1, @2)"; 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

77 

 
 
 
 
       db.Execute(insertCommand, title, genre, year); 
       Response.Redirect("~/Movies"); 
    } 
} 

Displaying Validation Errors 

The last step is to display any error messages. You can display individual messages for each 
validation error, or you can display a summary, or both. For this tutorial, you'll do both so that 
you can see how it works. 

Next to each <input> element that you're validating, call the Html.ValidationMessage method and 
pass it the name of the <input> element you're validating. You put the Html.ValidationMessage 
method right where you want the error message to appear. When the page runs, the 
Html.ValidationMessage method renders a <span> element where the validation error will go. (If 
there's no error, the <span> element is rendered, but there's no text in it.) 

Change the markup in the page so that it includes an Html.ValidationMessage method for each of 
the three <input> elements on the page, like this example: 

<p><label for="title">Title:</label> 
<input type="text" name="title" value="@Request.Form["title"]" /> 
      @Html.ValidationMessage("title") 
</p> 

<p><label for="genre">Genre:</label> 
<input type="text" name="genre" value="@Request.Form["genre"]" /> 
      @Html.ValidationMessage("genre") 
</p> 

<p><label for="year">Year:</label> 
<input type="text" name="year" value="@Request.Form["year"]" /> 
      @Html.ValidationMessage("year") 
</p> 

To see how the summary works, also add the following markup and code right after the <h1>Add a 
Movie</h1> element on the page: 

@Html.ValidationSummary() 

By default, the Html.ValidationSummary method displays all the validation messages in a list (a 
<ul> element that's inside a <div> element). As with the Html.ValidationMessage method, the 
markup for the validation summary is always rendered; if there are no errors, no list items are 
rendered.   

The summary can be an alternative way to display validation messages instead of by using the 
Html.ValidationMessage method to display each field-specific error. Or you can use both a 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

78 

 
 
summary and the details. Or you can use the Html.ValidationSummary method to display a generic 
error and then use individual Html.ValidationMessage calls to display details.  

The complete page now looks like this example: 

@{ 
    Validation.RequireField("title", "You must enter a title"); 
    Validation.RequireField("genre", "Genre is required"); 
    Validation.RequireField("year", "You haven't entered a year"); 

    var title = ""; 
    var genre = ""; 
    var year = ""; 

    if(IsPost && Validation.IsValid()){ 
       title = Request.Form["title"]; 
       genre = Request.Form["genre"]; 
       year = Request.Form["year"]; 

       var db = Database.Open("WebPagesMovies"); 
       var insertCommand = "INSERT INTO Movies (Title, Genre, Year) " +  
           " Values(@0, @1, @2)"; 
       db.Execute(insertCommand, title, genre, year); 
       Response.Redirect("~/Movies"); 
    } 
} 

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Add a Movie</title> 
</head> 
<body> 
<h1>Add a Movie</h1> 
  @Html.ValidationSummary() 
<form method="post"> 
<fieldset> 
<legend>Movie Information</legend> 
<p><label for="title">Title:</label> 
<input type="text" name="title" value="@Request.Form["title"]" /> 
          @Html.ValidationMessage("title") 
</p> 

<p><label for="genre">Genre:</label> 
<input type="text" name="genre" value="@Request.Form["genre"]" /> 
          @Html.ValidationMessage("genre") 
</p> 

<p><label for="year">Year:</label> 
<input type="text" name="year" value="@Request.Form["year"]" /> 
          @Html.ValidationMessage("year") 
</p> 

<p><input type="submit" name="buttonSubmit" value="Add Movie" /></p> 
</fieldset> 
</form> 
</body> 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

79 

 
 
 
 
 
 
 
</html> 

That's it. You can now test the page by adding a movie but leaving out one or more of the fields. 
When you do, you see the following error display: 

Styling the Validation Error Messages 

You can see that there are error messages, but they don't really stand out very well. There's an 
easy way to style the error messages, though.  

To style the individual error messages that are displayed by Html.ValidationMessage, create a CSS 
style class named field-validation-error. To define the look for the validation summary, create 
a CSS style class namedvalidation-summary-errors. 

To see how this technique works, add a <style> elementinside the <head> section of the page. 
Then define style classes named field-validation-error and validation-summary-errors that 
contain the following rules: 

<head> 
<meta charset="utf-8" /> 
<title>Add a Movie</title> 
<style type="text/css"> 
    .field-validation-error { 
      font-weight:bold; 
      color:red; 
      background-color:yellow; 
     } 
    .validation-summary-errors{ 
      border:2px dashed red; 
      color:red; 
      background-color:yellow; 
      font-weight:bold; 
      margin:12px; 
    } 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

80 

 
</style> 
</head> 

Normally you'd probably put style information into a separate .css file, but for simplicity you can 
put them in the page for now. (Later in this tutorial set, you'll move the CSS rules to a separate 
.css file.) 

If there's a validation error, the Html.ValidationMessage method renders a <span> element that 
includes class="field-validation-error". By adding a style definition for that class, you can 
configure what the message looks like. If there are errors, the ValidationSummary method likewise 
dynamically renders the attribute class="validation-summary-errors". 

Run the page again and deliberately leave out a couple of the fields. The errors are now more 
noticeable. (In fact, they're overdone, but that's just to show what you can do.) 

Adding a Link to the Movies Page 

One final step is to make it convenient to get to the AddMovie page from the original movie 
listing.  

Open the Movies page again. After the closing </div> tag that follows the WebGrid helper, add the 
following markup: 

<p> 
<a href="~/AddMovie">Add a movie</a> 
</p> 

As you saw before, ASP.NET interprets the ~ operator as the root of the website. You don't have 
to use the ~ operator; you could use the markup <a href="./AddMovie">Add a movie</a> or some 

Introducing ASP.NET Web Pages 2 

Tutorial 5: Entering Database Data by Using Forms 

81 

 
other way to define the path that HTML understands. But the ~ operator is a good general 
approach when you create links for Razor pages, because it makes the site more flexible β€” if you 
move the current page to a subfolder, the link will still go to the AddMovie page. (Remember that 
the ~ operator only works in .cshtml pages. ASP.NET understands it, but it's not standard HTML.) 

When you're done, run the Movies page. It will look like this page: 

Click the Add a movie link to make sure that it goes to the AddMovie page. 

Coming Up Next 

In the next tutorial, you'll learn how to let users edit data that's already in the database. 

Additional Resources 

β€’  Complete Listing for AddMovie Page 
β€’ 
β€’ 
β€’  Validating User Input in ASP.NET Web Pages Sites. More information about working with 

Introduction to ASP.NET Web Programming Using the Razor Syntax 
SQL INSERT INTO Statement on the W3Schools site 

the Validation helper.  

Tutorial 6: Updating Database Data 

This tutorial shows you how to update (change) an existing database entry when you use ASP.NET 
Web Pages (Razor). 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

82 

 
 
What you'll learn: 

β€’  How to select an individual record in the WebGrid helper. 
β€’  How to read a single record from a database. 
β€’  How to preload a form with values from the database record. 
β€’  How to update an existing record in a database. 
β€’  How to store information in the page without displaying it. 
β€’  How to use a hidden field to store information. 

Features/technologies discussed: 

β€’  The WebGrid helper. 
β€’  The SQL Update command. 
β€’  The Database.Execute method. 
β€’  Hidden fields (<input type="hidden">). 

What You'll Build 

In the previous tutorial, you learned how to add a record to a database. Here, you'll learn how to 
display a record for editing.In the Movies page, you'll update the WebGrid helper so that it displays 
an Edit link next to each movie:  

When you click the Edit link, it takes you to a different page, where the movie information is 
already in a form: 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

83 

 
You can change any of the values. When you submit the changes, the code in the page updates 
the database and takes you back to the movie listing.  

This part of the process works almost exactly like the AddMovie.cshtml page you created in the 
previous tutorial, so much of this tutorial will be familiar. 

There are several ways you could implement a way to edit an individual movie. The approach 
shown was chosen because it's easy to implement and easy to understand. 

Adding an Edit Link to the Movie Listing 

To begin, you'll update the Movies page so that each movie listing also contains an Edit link.  

Open the Movies.cshtml file.  

In the body of the page, change the WebGrid markup by adding a column. Here's the modified 
markup: 

@grid.GetHtml( 
    tableStyle: "grid", 
    headerStyle: "head", 
    alternatingRowStyle: "alt", 
    columns: grid.Columns( 
        grid.Column(format: @<a href="~/[email protected]">Edit</a>), 
        grid.Column("Title"), 
        grid.Column("Genre"), 
        grid.Column("Year") 
    ) 
)     

The new column is this one: 

grid.Column(format: @<a href="~/[email protected])">Edit</a>) 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

84 

 
The point of this column is to show a link (<a> element) whose text says "Edit". What we're after is 
to create a link that looks like the following when the page runs, with the id value different for 
each movie: 

http://localhost:43097/EditMovie?id=7 

This link will invoke a page named EditMovie, and it will pass the query string ?id=7 to that page. 

The syntax for the new column might look a bit complex, but that's only because it puts together 
several elements. Each individual element is straightforward. If you concentrate on just the <a> 
element, you see this markup: 

<a href="~/[email protected])">Edit</a> 

Some background about how the grid works: the grid displays rows, one for each database 
record, and it displays columns for each field in the database record. While each grid row is being 
constructed,the item object contains the database record (item) for that row. This arrangement 
gives you a way in code to get at the data for that row. That's what you see here: the expression 
item.ID is getting the ID value of the current database item. You could get any of the database 
values (title, genre, or year) the same way by using item.Title, item.Genre, or item.Year. 

The expression "~/[email protected] combines the hard-coded part of the target URL 
(~/EditMovie?id=) with this dynamically derived ID. (You saw the ~ operator in the previous 
tutorial; it's an ASP.NET operator that reprethe current website root.) 

The result is that this part of the markup in the column simply produces something like the 
following markup at run time: 

href="/EditMovie?id=2" 

Naturally, the actual value of id will be different for each row. 

Creating a Custom Display for a Grid Column 

Now back to the grid column. The three columns you originally had in the grid displayed only data 
values (title, genre, and year). You specified this display by passing the name of the database 
column β€” for example, grid.Column("Title").   

This new Edit link column is different. Instead of specifying a column name, you're passing a 
format parameter. This parameter lets you define markup that the WebGrid helper will render 
along with the item valueto display the column data as bold or green or in whatever format that 
you want. For example, if you wanted the title to appear bold, you could create a column like this 
example: 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

85 

grid.Column(format:@<strong>@item.Title</strong>) 

(The various @ characters you see in the format property mark the transition between markup and 
a code value.) 

Once you know about the format property, it's easier to understand how the new Edit link column 
is put together:  

grid.Column(format: @<a href="~/[email protected]">Edit</a>), 

The column consists only of the markup that renders the link, plus some information (the ID) 
that's extracted from the database record for the row. 

Named Parameters and Positional Parameters for a Method 

Many times when you've called a method and passed parameters to it, you've simply listed the 
parameter values separated by commas. Here are a couple of examples: 

db.Execute(insertCommand, title, genre, year) 

Validation.RequireField("title", "You must enter a title") 

We didn't mention the issue when you first saw this code, but in each case, you're passing 
parameters to the methods in a specific order β€” namely, the order in which the parameters are 
defined in that method. For db.Execute and Validation.RequireFields, if you mixed up the order 
of the values you pass, you'd get an error message when the page runs, or at least some strange 
results. Clearly, you have to know the order to pass the parameters in. (In WebMatrix, IntelliSense 
can help you learn figure out the name, type, and order of the parameters.) 

As an alternative to passing values in order, you can use named parameters. (Passing parameters 
in order is known as using positional parameters.) For named parameters, you explicitly include 
the name of the parameter when passing its value. You've used named parameters already a 
number of times in these tutorials. For example: 

var grid = new WebGrid(source: selectedData, defaultSort: "Genre", rowsPerPage:3) 

and 

@grid.GetHtml( 
    tableStyle: "grid", 
    headerStyle: "head", 
    alternatingRowStyle: "alt", 
    columns: grid.Columns( 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

86 

       grid.Column("Title"), 
       grid.Column("Genre"), 
       grid.Column("Year") 
    ) 
) 

Named parameters are handy for a couple of situations, especially when a method takes many 
parameters. One is when you want to pass only one or two parameters, but the values you want 
to pass are not among the first positions in the parameter list. Another situation is when you want 
to make your code more readable by passing the parameters in the order that makes the most 
sense to you.  

Obviously, to use named parameters, you have to know the names of the parameters. WebMatrix 
IntelliSense can show you the names, but it cannot currently fill them in for you.  

Creating the Edit Page 

Now you can create the EditMovie page. When users click the Edit link, they'll end up on this 
page. 

Create a page named EditMovie.cshtml and replace what's in the file with the following markup: 

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Edit a Movie</title> 
<style> 
      .validation-summary-errors{ 
        border:2px dashed red; 
        color:red; 
        font-weight:bold; 
        margin:12px; 
      } 
</style> 
</head> 
</head> 
<body> 
<h1>Edit a Movie</h1> 
    @Html.ValidationSummary() 
<form method="post"> 
<fieldset> 
<legend>Movie Information</legend> 

<p><label for="title">Title:</label> 
<input type="text" name="title" value="@title" /></p> 

<p><label for="genre">Genre:</label> 
<input type="text" name="genre" value="@genre" /></p> 

<p><label for="year">Year:</label> 
<input type="text" name="year" value="@year" /></p> 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

87 

 
 
 
<input type="hidden" name="movieid" value="@movieId" /> 

<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p> 
</fieldset> 
</form> 
</body> 
</html> 

This markup and code is similar to what you have in the AddMovie page. There's a small 
difference in the text for the submit button. As with the AddMovie page, there's an 
Html.ValidationSummary call that will display validation errors if there are any. This time we're 
leaving out calls to Validation.Message, since errors will be displayed in the validation summary. 
As noted in the previous tutorial, you can use the validation summary and the individual error 
messages in various combinations.  

Notice again that the method attribute of the <form> element is set to post. As with the 
AddMovie.cshtml page, this page makes changes to the database. Therefore, this form should 
perform a POST operation. (For more about the difference between GET and POST operations, see 
the GET, POST, and HTTP Verb Safety sidebar in the tutorial on HTML forms.) 

As you saw in an earlier tutorial, the value attributes of the text boxes are being set with Razor 
code in order to preload them. This time, though, you're using variables like title and genre for 
that task instead of Request.Form["title"]: 

<input type="text" name="title" value="@title" /> 

As before, this markup will preload the text box values with the movie values. You'll see in a 
moment why it's handy to use variables this time instead of using the Request object. 

There's also a <input type="hidden"> element on this page. This element stores the movie ID 
without making it visible on the page. The ID is initially passed to the page by using a query string 
value (?id=7 or similar in the URL).By putting the ID value into a hidden field, you can make sure 
that it's available when the form is submitted, even if you no longer have access to the original 
URL that the page was invoked with. 

Unlike the AddMovie page, the code for the EditMovie page has two distinct functions. The first 
function is that when the page is displayed for the first time (and only then), the code gets the 
movie ID from the query string. The code then uses the ID to read the corresponding movie out of 
the database and display (preload) it in the text boxes. 

The second function is that when the user clicks the Submit Changes button, the code has to read 
the values of the text boxes and validate them. The code also has to update the database item 
with the new values. This technique is similar to adding a record, as you saw in AddMovie. 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

88 

 
 
Adding Code to Read a Single Movie 

To perform the first function, add this code to the top of the page: 

@{ 
    var title = ""; 
    var genre = ""; 
    var year = ""; 
    var movieId = ""; 

    if(!IsPost){ 
        if(!Request.QueryString["ID"].IsEmpty()){ 
            movieId = Request.QueryString["ID"]; 
            var db = Database.Open("WebPagesMovies"); 
            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 
            var row = db.QuerySingle(dbCommand, movieId); 
            title = row.Title; 
            genre = row.Genre; 
            year = row.Year; 
        } 
        else{ 
            Validation.AddFormError("No movie was selected."); 
            // If you are using a version of ASP.NET Web Pages 2 that's  
            // earlier than the RC release, comment out the preceding  
            // statement and uncomment the following one. 
            //ModelState.AddFormError("No movie was selected."); 
        }     
    } 
} 

Most of this code is inside a block that starts if(!IsPost). The ! operator means "not,"so the 
expression means if this request is not a post submission, which is an indirect way of saying if this 
request is the first time that this page has been run. As noted earlier, this code should run only the 
first time the page runs. If you didn't enclose the code in if(!IsPost), it would run every time the 
page is invoked, whether the first time or in response to a button click. 

Notice that the code includes an else block this time. As we said when we introduced if blocks, 
sometimes you want to run alternative code if the condition you're testing isn't true. That's the 
case here. If the condition passes (that is, if the ID passed to the page is ok), you read a row from 
the database. However, if the condition doesn't pass, the else block runs and the code sets an 
error message. 

Validating a Value Passed to the Page 

The code uses Request.QueryString["id"] to get the ID that's passed to the page. The code 
makes sure that a value was actually passed for the ID. If no value was passed, the code sets a 
validation error.  

This code shows a different way to validate information. In the previous tutorial, you worked with 
the Validation helper. You registered fields to validate, and ASP.NET automatically did the 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

89 

 
validation and displayed errors by using Html.ValidationMessage and Html.ValidationSummary. In 
this case, however, you're not really validating user input. Instead,you're validating a value that 
was passed to the page from elsewhere. The Validation helper doesn't do that for you. 

Therefore, you check the value yourself, by testing it 
withif(!Request.QueryString["ID"].IsEmpty()). If there's a problem, you can display the error by 
using Html.ValidationSummary, as you did with the Validation helper. To do that, you call 
Validation.AddFormError and pass it a message to display. Validation.AddFormError is a built-in 
method that lets you define custom messages that tie in with the validation system you're already 
familiar with. (Later in this tutorial we'll talk about how to make this validation process a little 
more robust.) 

Note   If you're using a version of ASP.NET Web Pages 2 earlier than the RC release (for 
example, if you're using the Beta refresh release from February 2012), use 
ModelState.AddFormError instead of Validation.AddFormError. The AddFormError method 
was added to the Validation helper in the RC release. 

After making sure that there's an ID for the movie, the code reads the database, looking for only a 
single database item. (You probably have noticed the general pattern for database operations: 
open the database, define a SQL statement, and run the statement.) This time, the SQL Select 
statement includes WHERE ID = @0. Because the ID is unique, only one record can be returned.  

The query is performed by using db.QuerySingle (not db.Query, as you used for the movie listing), 
and the code puts the result into the row variable. The name row is arbitrary; you can name the 
variables anything you like.The variables initialized at the top are then filled with the movie details 
so that these values can be displayed in the text boxes. 

Testing the Edit Page (So Far) 

If you'd like to test your page, run the Movies page now and click an Edit link next to any movie. 
You'll see the EditMovie page with the details filled in for the movie you selected: 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

90 

 
Notice that the URL of the page includes something like ?id=10 (or some other number). So far 
you've tested that Edit links in the Movie page work, that your page is reading the ID from the 
query string, and that the database query to get a single movie record is working. 

You can change the movie information, but nothing happens when you click Submit Changes.  

Adding Code to Update the Movie with the User's Changes 

In the EditMovie.cshtml file, to implement the second function (saving changes), add the following 
code just inside the closing bracket of the @ block. (If you're sure exactly where to put the code, 
you can look at the complete page listing for the Edit Movie page that appears at the end of this 
tutorial.) 

    if(IsPost){ 
        Validation.RequireField("title", "You must enter a title"); 
        Validation.RequireField("genre", "Genre is required"); 
        Validation.RequireField("year", "You haven't entered a year"); 
        Validation.RequireField("movieid", "No movie ID was submitted!"); 

        title = Request.Form["title"]; 
        genre = Request.Form["genre"]; 
        year = Request.Form["year"]; 
        movieId = Request.Form["movieId"]; 

        if(Validation.IsValid()){     
            var db = Database.Open("WebPagesMovies"); 
            var updateCommand = "UPDATE Movies " +  
                   "SET Title=@0, Genre=@1, Year=@2 WHERE Id=@3"; 
            db.Execute(updateCommand, title, genre, year, movieId); 
            Response.Redirect("~/Movies"); 
       } 
    } 

Again, this markup and code is similar to the code in AddMovie. The code is in an if(IsPost) 
block, because this code runs only when the user clicks the Submit Changes button β€” that is, 
when (and only when) the form has been posted. In this case, you're not using a test like 
if(IsPost && Validation.IsValid()) β€” that is,you're not combining both tests by using AND. In 
this page, you first determine whether there's a form submission (if(IsPost)), and only then 
register the fields for validation. Then you can test the validation results 
(if(Validation.IsValid()). The flow is slightly different than in the AddMovie.cshtml page, but 
the effect is the same. 

You get the values of the text boxes by using Request.Form["title"] and similar code for the 
other <input> elements. Notice that this time, the code gets the movie ID out of the hidden field 
(<input type="hidden">). When the page ran the first time, the code got the ID out of the query 
string. You get the value from the hidden field to make sure that you're getting the ID of the 
movie that was originally displayed, in case the query string was somehow altered since then. 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

91 

 
 
The really important difference between the AddMovie code and this code is that in this code you 
use the SQL Update statement instead of the Insert Into statement. The following example 
shows the syntax of the SQL Update statement: 

UPDATE table SET col1="value", col2="value", col3="value" ... WHERE ID = value 

You can specify any columns in any order, and you don't necessarily have to update every column 
during an Update operation. (You cannot update the ID itself, because that would in effect save 
the record as a new record, and that's not allowed for an Update operation.)  

Important   The Where clause with the ID is very important, because that's how the 
database knows which database record you want to update. If you left off the Where 
clause, the database would update every record in the database. In most cases, that would 
be a disaster. 

In the code, the values to update are passed to the SQL statement by using placeholders. To 
repeat what we've said before: for security reasons, only use placeholders to pass values to a SQL 
statement. 

After the code uses db.Execute to run the Update statement,it redirects back to the listing page, 
where you can see the changes. 

Different SQL Statements, Different Methods 

You might have noticed that you use slightly different methods to run different SQL statements. 
To run a Select query that potentially returns multiple records, you use the Query method. To run 
a Select query that you know will return only one database item, you use the QuerySingle 
method. To run commands that make changes but that don't return database items, you use the 
Execute method. 

You have to have different methods because each of them returns different results, as you saw 
already in the difference between Query and QuerySingle. (The Execute method actually returns a 
value also β€” namely, the number of database rows that were affected by the command β€” but 
you've been ignoring that so far.)  

Of course, the Query method might return only one database row. However, ASP.NET always 
treats the results of the Query method as a collection. Even if the method returns just one row, 
you have to extract that single row from the collection. Therefore, in situations where you know 
you'll get back only one row, it's a bit more convenient to use QuerySingle. 

There are a few other methods that perform specific types of database operations. You can find a 
listing of database methods in the ASP.NET Web Pages API Quick Reference. 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

92 

Making Validation for the ID More Robust 

The first time that the page runs, you get the movie ID from the query string so that you can go 
get that movie from the database. You made sure that there actually was a value to go look for, 
which you did by using this code: 

if(!IsPost){ 
    if(!Request.QueryString["ID"].IsEmpty()){ 
        // Etc. 
    } 
} 

You used this code to make sure that if a user gets to the EditMovies page without first selecting a 
movie in the Movies page, the page would display a user-friendly error message. (Otherwise, 
users would see an error that would probably just confuse them.) 

However, this validation isn't very robust. The page might also be invoked with these errors: 

β€’  The ID isn't a number. For example, the page could be invoked with a URL like 

http://localhost:nnnnn/EditMovie?id=abc. 

β€’  The ID is a number, but it references a movie that doesn't exist (for example, 

http://localhost:nnnnn/EditMovie?id=100934). 

If you're curious to see the errors that result from these URLs, run the Movies page. Select a 
movie to edit, and then change the URL of the EditMovie page to a URL that contains an 
alphabetic ID or the ID of a non-existent movie. 

So what should you do? The first fix is to make sure that not only is an ID passed to the page, but 
that the ID is an integer. Change the code for the !IsPost test to look like this example: 

if(!IsPost){ 
    if(!Request.QueryString["ID"].IsEmpty() && Request.QueryString["ID"].IsInt()) 
{ 
       // Etc. 

You've added a second condition to the IsEmpty test, linked with && (logical AND): 

Request.QueryString["ID"].IsInt() 

You might remember from the Programming Basics tutorial that methods like AsBool an AsInt 
convert a character string to some other data type. The IsInt method (and others, like IsBool and 
IsDateTime) are similar. However, they test only whether you can convert the string, without 
actually performing the conversion. So here you're essentially saying If the query string value can 
be converted to an integer ... . 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

93 

The other potential problem is looking for a movie that doesn't exist. The code to get a movie 
looks like this code: 

var row = db.QuerySingle(dbCommand, movieId); 

If you pass a movieId value to the QuerySingle method that doesn't correspond to an actual 
movie, nothing is returned and the statements that follow (for example, title=row.Title) result 
in errors.  

Again there's an easy fix. If the db.QuerySingle method returns no results, the row variable will be 
null. So you can check whether the row variable is null before you try to get values from it. The 
following code adds an if block around the statements that get the values out of the row object: 

if(row != null) { 
    title = row.Title; 
    genre = row.Genre; 
    year = row.Year; 
} 
else{ 
    Validation.AddFormError("No movie was found for that ID."); 
    // Use the following line instead for versions of ASP.NET Web Pages 2 earlier 
    // than the RC release. 
    //ModelState.AddFormError("No movie was found for that ID."); 
} 

With these two additional validation tests, the page becomes more bullet-proof. The complete 
code for the !IsPost branch now looks like this example: 

if(!IsPost){ 
     if(!Request.QueryString["ID"].IsEmpty() && Request.QueryString["ID"].IsInt()) 
{ 
        movieId = Request.QueryString["ID"]; 
        var db = Database.Open("WebPagesMovies"); 
        var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 
        var row = db.QuerySingle(dbCommand, movieId); 

        if(row != null) { 
            title = row.Title; 
            genre = row.Genre; 
             year = row.Year; 
        } 
        else{ 
               Validation.AddFormError("No movie was found for that ID."); 
               // Use the following line instead for versions of ASP.NET  
               // Web Pages 2 earlierthan the RC release. 
               //ModelState.AddFormError("No movie was found for that ID."); 
        } 
    }     
    else{ 
        Validation.AddFormError("No movie was selected.") 
        // Use the following line instead for versions of ASP.NET  
        // Web Pages 2 earlierthan the RC release. 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

94 

 
        //ModelState.AddFormError("No movie was selected."); 
    }     
} 

We'll note once more that this task is a good use for an else block. If the tests don't pass, the else 
blocks set error messages. 

Adding a Link to Return to the Movies Page 

A final and helpful detail is to add a link back to the Movies page. In the ordinary flow of events, 
users will start at the Movies page and click an Edit link. That brings them to the EditMovie page, 
where they can edit the movie and click the button. After the code processes the change, it 
redirects back to the Movies page. 

However: 

β€’  The user might decide not to change anything.  
β€’  The user might have gotten to this page without first clicking an Edit link in the Movies 

page. 

Either way, you want to make it easy for them to return to the main listing. It's an easy fix β€” add 
the following markup just after the closing </form> tag in the markup:  

<p><a href="~/Movies">Return to movie listing</a></p> 

This markup uses the same syntax for an <a> element that you've seen elsewhere. The URL 
includes ~ to mean "root of the website." 

Testing the Movie Update Process 

Now you can test. Run the Movies page,and click Edit next to a movie. When the EditMovie page 
appears, make changes to the movie and clickSubmit Changes. When the movie listing appears, 
make sure that your changes are shown. 

To make sure that validation is working, click Edit for another movie. When you get to the 
EditMovie page, clear the Genre field (or Year field, or both) and try to submit your changes. 
You'll see an error, as you'd expect: 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

95 

Click the Return to movie listing link to abandon your changes and return to the Movies page. 

Coming Up Next 

In the next tutorial,you'll see how to delete a movie record. 

Additional Resources 

β€’  Complete Listing for Movie Page (Updated with Edit Links) 
β€’  Complete Page Listing for Edit Movie Page 
β€’ 

SQL UPDATE Statement on the W3Schools site 

Introducing ASP.NET Web Pages 2 

Tutorial 6: Updating Database Data 

96 

 
 
 
Tutorial 7: Deleting Database Data 

This tutorial shows you how to delete an individual database entry.  

What you'll learn: 

β€’  How to select an individual record from a listing of records. 
β€’  How to delete a single record from a database. 
β€’  How to check that a specific button was clicked in a form. 

Features/technologies discussed: 

β€’  The WebGrid helper. 
β€’  The SQL Delete command. 
β€’  The Database.Execute method to run a SQL Delete command. 

What You'll Build 

In the previous tutorial, you learned how to update an existing database record.This tutorial is 
similar, except that instead of updating the record,you'll delete it. The processes are much the 
same, except that deleting issimpler, so this tutorial will be short. 

In the Movies page,you'll update the WebGrid helper so that it displays a Delete link next to each 
movie to accompany the Editlink you added earlier.  

As with editing, when you click the Delete link, it takes you to a differentpage, where the movie 
information is already in a form: 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

97 

 
You can then click the button to delete the record permanently.  

Adding a Delete Link to the Movie Listing 

You'll start by adding a Delete link to the WebGrid helper. This link is similar to the Edit link you 
added in aprevious tutorial. 

Open the Movies.cshtml file.  

Change the WebGrid markup in the body of the page by adding acolumn. Here's the modified 
markup: 

@grid.GetHtml( 
    tableStyle: "grid", 
    headerStyle: "head", 
    alternatingRowStyle: "alt", 
    columns: grid.Columns( 

grid.Column(format: @<a href="~/[email protected]">Edit</a>), 
grid.Column("Title"), 
grid.Column("Genre"), 
grid.Column("Year"), 
grid.Column(format: @<a href="~/[email protected]">Delete</a>) 

    ) 
) 

The new column is this one: 

grid.Column(format: @<a href="~/[email protected]">Delete</a>) 

The way the grid is configured, the Edit column is leftmostin the grid and the Delete column is 
rightmost. (There's acomma after the Year column now, in case you didn't notice that.)There's 
nothing special about where these link columns go, and you could aseasily put them next to each 
other. In this case, they're separate to make them harder to get mixed up. 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

98 

 
 
 
 
 
 
The new column shows a link (<a> element)whose text says "Delete". The target of the link (its 
href attribute)is code that ultimately resolves to something like this URL, with the idvalue 
different for each movie: 

http://localhost:43097/DeleteMovie?id=7 

This link will invoke a page named DeleteMovie and pass it the ID of themovie you've selected.  

This tutorial won't go into detail about how this link is constructed,because it's almost identical to 
the Edit link from theprevious tutorial (Updating Database Data).  

Creating the Delete Page 

Now you can create the page that will be the target for the Deletelink in the grid. 

Important The technique of firstselecting a record to delete and then using a separate 
page and button to confirm the process is extremely important for security. As you've read 
in previous tutorials, making any sort of change toyour website should alwaysbe done 
using a form β€” that is, using an HTTP POST operation. If you made itpossible to change the 
site just by clicking a link (that is, using a GEToperation), people could make simple 
requests to your site and delete your data. Even a search-engine crawler that's indexing 
your site could inadvertently delete data just by following links.  

When your app lets people change a record, you have to present the record to the user for editing 
anyway. Butyou might be tempted to skip this step for deleting a record. Don't skip that step, 
though. (It's also helpful for users to see the record and confirm that they're deleting the record 
that they intended.) 

In a subsequent tutorial set, you'll see how to add loginfunctionality so a user would have to log in 
before deleting a record. 

Create a page named DeleteMovie.cshtml and replace what's in the file with the following 
markup: 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

99 

 
 
<html> 
<head> 
  <title>Delete a Movie</title> 
</head> 
<body> 
      <h1>Delete a Movie</h1> 
        @Html.ValidationSummary() 
      <p><a href="~/Movies">Return to movie listing</a></p> 

      <form method="post"> 
        <fieldset> 
        <legend>Movie Information</legend> 

        <p><span>Title:</span> 
         <span>@title</span></p> 

        <p><span>Genre:</span> 
         <span>@genre</span></p> 

        <p><span>Year:</span> 
          <span>@year</span></p> 

        <input type="hidden" name="movieid" value="@movieId" /> 
        <p><input type="submit" name="buttonDelete" value="Delete Movie" /></p> 
        </fieldset> 
      </form>  
    </body> 
</html> 

This markup is like the EditMovie pages, except that instead of using textboxes 
(<input type="text">), the markup includes <span>elements. There's nothing here to edit. All you 
have to do is display the moviedetails so that users can make sure that they're deleting the right 
movie. 

The markup already contains a link that lets the user return to the movielisting page. 

As in the EditMovie page, the ID of the selected movie is stored ina hidden field. (It's passed into 
the page in the first place as a query stringvalue.)There's an Html.ValidationSummary call thatwill 
display validation errors. In this case, the errormight be that no movie ID was passed to the page 
or that the movie ID is invalid. This situation could occur if someoneran this page without first 
selecting a movie in the Movies page. 

The button caption is Delete Movie, and its name attributeis set to buttonDelete. The name 
attribute will be usedin the code to identify the button that submitted the form.  

You'll have to write code to 1) read the movie details when the page is firstdisplayed and 2) 
actually delete the movie when the user clicks the button. 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

100 

 
 
       
       
 
 
Adding Code to Read a Single Movie 

At the top of the DeleteMovie.cshtml page, add the following codeblock: 

@{ 
    var title = ""; 
    var genre = ""; 
    var year = ""; 
    var movieId = ""; 

    if(!IsPost){ 
        if(!Request.QueryString["ID"].IsEmpty() && 
Request.QueryString["ID"].IsInt()){ 
            movieId = Request.QueryString["ID"]; 
            var db = Database.Open("WebPagesMovies"); 
            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 
            var row = db.QuerySingle(dbCommand, movieId); 
            if(row != null) { 
                title = row.Title; 
                genre = row.Genre; 
                year = row.Year; 
            } 
            else{ 
                Validation.AddFormError("No movie was found for that ID."); 
                // If you are using a version of ASP.NET Web Pages 2 that's  
                // earlier than the RC release, comment out the preceding  
                // statement and uncomment the following one. 
                //ModelState.AddFormError("No movie was found for that ID."); 
            } 
        } 
        else{ 
            Validation.AddFormError("No movie was found for that ID."); 
            // If you are using a version of ASP.NET Web Pages 2 that's  
            // earlier than the RC release, comment out the preceding  
            // statement and uncomment the following one. 
            //ModelState.AddFormError("No movie was found for that ID."); 
        }     
    } 
} 

This markup is the same as the corresponding code in the EditMovie page. It gets the movie ID out 
of the query string and uses the ID to read a recordfrom the database. The code includes the 
validation test (IsInt()and row != null) to make sure that the movie ID being passed to thepage 
is valid.  

Remember that this code should only run the first time the page runs. You don't want to re-read 
the movie record from the database when the user clicksthe Delete Movie button.Therefore, 
code to read the movie is inside a test that says if(!IsPost) β€” that is, if the request is not a post 
operation (form submission). 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

101 

 
Adding Code to Delete the Selected Movie 

To delete the movie when the user clicks the button, add the following codejust inside the closing 
bracket of the @ block: 

    if(IsPost && !Request["buttonDelete"].IsEmpty()){ 
        movieId = Request.Form["movieId"]; 
        var db = Database.Open("WebPagesMovies"); 
        var deleteCommand = "DELETE FROM Movies WHERE ID = @0"; 
        db.Execute(deleteCommand, movieId); 
        Response.Redirect("~/Movies"); 
    } 

This code is similar to the code for updating an existing record, but simpler. The  code basically 
runs a SQL Delete statement.  

As in the EditMovie page, the code is inan if(IsPost) block. This time, the if() condition isa little 
more complicated:  

if(IsPost && !Request["buttonDelete"].IsEmpty()) 

There are two conditions here. The first is that the page is being submitted,as you've seen before 
β€” if(IsPost).  

The second condition is !Request["buttonDelete"].IsEmpty(),meaning that the request has an 
object named buttonDelete.Admittedly, it's an indirect way of testing which buttonsubmitted the 
form. If a form contains multiple submit buttons, only the name ofthe button that was clicked 
appears in the request. Therefore, logically, ifthe name of a particular button appears in the 
request β€” or as stated in thecode, if that button isn't empty β€” that's the button that submitted 
the form. 

The && operator means "and" (logical AND). Therefore the entire if condition is ...  

This request is a post (not a first-time request) 

AND 

The buttonDelete button was the button that submitted the form. 

This form (in fact, this page) contains only one button, so the additional testfor buttonDelete is 
technically not required. Still, you're about to perform an operation that will permanently remove 
data. So you want to be as sure as possible that you're performing the operation only when the 
user hasexplicitly requested it. For example, suppose that you expanded this page later and 
addedother buttons to it. Even then, the code that deletes the moviewill run only if the 
buttonDelete button was clicked.  

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

102 

 
 
As in the EditMovie page, you get the ID from the hidden field andthen run the SQL command. 
The syntax for the Delete statement is: 

DELETE FROM table WHERE ID = value 

It's vital to include the WHERE clause and the ID. If you leaveout the WHERE clause, all the records 
in the table will be deleted. As youhave seen, you pass the ID value to the SQL command by using 
a placeholder. 

Testing the Movie Delete Process 

Now you can test. Run the Movies page, and click Deletenext to a movie. When the DeleteMovie 
page appears, click Delete Movie.  

When you click the button, the code deletes the movies and returns to themovie listing. There 
you can search for the deleted movie and confirm that it's been deleted. 

Coming Up Next 

The next tutorial shows you how to give all the pages on your site a commonlook and layout. 

Additional Resources 

β€’  Complete Listing for Movie Page (Updated with Delete Links) 
β€’  Complete Listing for DeleteMovie Page 
β€’ 
β€’  SQL DELETE Statement on the W3Schools site 

Introduction to ASP.NET Web Programming by Using the Razor Syntax 

Introducing ASP.NET Web Pages 2 

Tutorial 7: Deleting Database Data 

103 

 
Tutorial 8: Creating a Consistent Layout 

This tutorial shows you how to use layouts to create a consistent look for the pages on a site that 
uses ASP.NET Web Pages. 

What you'll learn: 

β€’  What a layout page is. 
β€’  How to combine layout pages with dynamic content. 
β€’  How to pass values to a layout page. 

About Layouts 

The pages you've created so far have all been complete, standalone pages. They all belong to the 
same site, but they don't have any common elements or a standard look.  

Most sites do have a consistent look and layout. For example, if you go to the Microsoft.com/web 
site and look around, you see that the pages all adhere to an overall layout and to a visual theme: 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

104 

An inefficient way to create this layout would be to define a header, navigation bar, and footer 
separately on each of your pages. You'd be duplicating the same markup each time. If you wanted 
to change something (for example, update the footer), you'd have to change each page 
separately.  

That's where layout pages come in. In ASP.NET Web Pages, you can define a layout page that 
provides an overall container for pages on your site. For example, the layout page can contain the 
header, navigation area, and footer. The layout page includes a placeholder where the main 
content goes.  

You can then define individual content pages that contain the markup and the code for only that 
page. Content pages don't have to be complete HTML pages; they don't even have to have a 
<body> element. They also have a line of code that tells ASP.NET what layout page you want to 
display the content in. Here's a picture that shows roughly how this relationship works: 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

105 

 
This interaction is easy to understand when you see it in action. In this tutorial, you'll change your 
movies pages to use a layout. 

Adding a Layout Page 

You'll start by creating a layout page that defines a typical page layout with a header, footer, and 
an area for the main content. In the WebPagesMovies site, add a CSHTML page named 
_Layout.cshtml.  

The leading underscore ( _ ) character is significant. If a page's name starts with an underscore, 
ASP.NET won't directly send that page to the browser. This convention lets you define pages that 
are required for your site but that users shouldn't be able to request directly. 

Replace the content in the page with the following: 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

106 

 
 
<!DOCTYPE html> 
<html> 
<head> 
<title>@Page.Title</title> 
<link href="~/Styles/Movies.css" rel="stylesheet" type="text/css" /> 
</head> 
<body> 
<div id="container"> 
<div id="header"> 
<h1>My Movie Site</h1> 
</div> 
<div id="main"> 
          @RenderBody() 
</div> 
<div id="footer"> 
&copy; @DateTime.Now.Year My Movie Site 
</div> 
</div> 
</body> 
</html> 

As you can see, this markup is just HTML that uses <div> elements to define three sections in the 
page plus one more <div> element to hold the three sections. The footer contains a bit of Razor 
code: @DateTime.Now.Year, which will render the current year at that location in the page. 

Notice that there's a link to a style sheet named Movies.css. The style sheet is where the details of 
the physical layout of the elements will be defined. You'll create that in a moment. 

The only unusual feature in this _Layout.cshtml page is the @Render.Body() line. That's the 
placeholder where the content will go when this layout is merged with another page.  

Adding a .css File 

The preferred way to define the actual arrangement (that is, appearance) of elements on the 
page is to use cascading style sheet (CSS) rules. So you'll create a .css file that has the rules for 
your new layout.  

In WebMatrix, select the root of your site. Then in the Files tab of the ribbon, click the arrow 
under the New button and then click New Folder. 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

107 

 
Name the new folder Styles. 

Inside the new Styles folder, create a file named Movies.css.  

Replace the contents of the new .css file with the following: 

html{ height:100%; margin:0; padding:0; } 

body { 
  height:60%; 
  font-family:'Trebuchet MS',  'Arial', 'Helvetica', 'sans-serif'; 
  font-size:10pt; 
  background-color: LightGray; 
  line-height:1.6em; 
} 

h1{ font-size:1.6em; } 
h2{ font-size:1.4em; } 

#container{ 
   min-height:100%; 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

108 

 
 
 
 
 
   position:relative; 
   left:10%; 
} 

#header{ 
  padding:8px; 
  width:80%; 
  background-color:#4b6c9e; 
  color:White; 
} 

#main{ 
  width:80%; 
  padding: 8px; 
  padding-bottom:4em; 
  background-color:White; 
} 

#footer{ 
  position:absolute; 
  bottom:0; 
  width:80%; 
  height:2em; 
  padding:8px; 
  margin-top:-2em; 
  background-color:LightGray; 
} 

.head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 
.grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 
.alt { background-color: #E8E8E8; color: #000; } 
.selected {background-color:Yellow;} 
span.caption {width:100px;} 
span.dataDisplay {font-weight:bold;} 

We won't say much about these CSS rules, except to note two things. One is that in addition to 
setting fonts and sizes, the rules use absolute positioning to establish the location of the header, 
footer, and main content area. If you're new to positioning in CSS, you can read the CSS 
Positioning tutorial at the W3Schools site. 

The other thing to note is that at the bottom, we've copied the style rules that were originally 
defined individually in the Movies.cshtml file. These rules were used in the Displaying Data 
tutorial to make the WebGrid helper render markup that added stripes to the table. (If you're going 
to use a .css file for style definitions, you might as well put the style rules for the whole site in it.)  

Updating the Movies File to Use the Layout 

Now you can update the existing files in your site to use the new layout. Open the Movies.cshtml 
file. At the top, as the first line of code, add the following: 

Layout = "~/_Layout.cshtml"; 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

109 

 
 
 
 
The page now starts out this way: 

@{ 
    Layout = "~/_Layout.cshtml"; 

    var db = Database.Open("WebPagesMovies") ; 
    var selectCommand = "SELECT * FROM Movies"; 
    var searchTerm = ""; 

    // Etc. 

This one line of code tells ASP.NET that when the Movies page runs, it should be merged with the 
_Layout.cshtml file. 

Since the Movies.cshtml file now uses a layout page, you can remove the markup from the 
Movies.cshtml page that's taken care of by the _Layout.cshtml file. Take out the <!DOCTYPE>, 
<html>,and <body> opening and closing tags. Take out the entire <head> element and its contents, 
which includes the style rules for the grid, since you've now got those rules in a .css file.While 
you're at it, change the existing <h1> element to an <h2> element; you have an <h1> element in the 
layout page already. Change the <h2> text to "List Movies". 

Normally you wouldn't have to make these sorts of changes in a content page. When you start 
your site out with a layout page, you create content pages without all these elementsto begin 
with. In this case, though, you're converting a standalone page to one that uses a layout, so 
there's a bit of cleanup.  

When you're finished, the Movies.cshtml page will look like the following: 

@{ 
    Layout = "~/_Layout.cshtml"; 

    var db = Database.Open("WebPagesMovies") ; 
    var selectCommand = "SELECT * FROM Movies"; 
    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  
        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 
        searchTerm = Request.QueryString["searchGenre"]; 
    } 

    if(!Request.QueryString["searchTitle"].IsEmpty() ) {  
      selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 
      searchTerm = "%" + Request.QueryString["searchTitle"] + "%";  
    } 

    var selectedData = db.Query(selectCommand, searchTerm); 
    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  
rowsPerPage:3); 
} 
<h2>List Movies</h2> 
<form method="get"> 
<div> 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

110 

 
 
 
 
 
 
<label for="searchGenre">Genre to look for:</label> 
<input type="text" name="searchGenre"  
         value="@Request.QueryString["searchGenre"]" /> 
<input type="Submit" value="Search Genre" /><br/> 
      (Leave blank to list all movies.)<br/> 
</div> 
<div> 
<label for="SearchTitle">Movie title contains the following:</label> 
<input type="text" name="searchTitle"  
value="@Request.QueryString["searchTitle"]" /> 
<input type="Submit" value="Search Title" /><br/> 
</div> 
</form> 
<div> 
    @grid.GetHtml( 
        tableStyle: "grid", 
        headerStyle: "head", 
        alternatingRowStyle: "alt", 
        columns: grid.Columns( 
            grid.Column(format: @<a href="~/[email protected]">Edit</a>), 
            grid.Column("Title"), 
            grid.Column("Genre"), 
            grid.Column("Year"), 
            grid.Column(format: @<a href="~/[email protected]">Delete</a>) 
       ) 
    ) 
</div> 
<p><a href="~/AddMovie">Add a movie</a></p> 

Testing the Layout 

Now you can see what the layout looks like. In WebMatrix, right-click the Movies.cshtml page and 
select Launch in browser. When the browser displays the page, it looks like this page: 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

111 

ASP.NET has merged the content of the Movies.cshtml page into the _Layout.cshtml page right 
where the RenderBody method is. And of course the _Layout.cshtml page references a .css file that 
defines the look of the page. 

Updating the AddMovie Page to Use the Layout 

The real benefit of layouts is that you can use them for all the pages in your site. Open the 
AddMovie.cshtml page. 

You might remember that the AddMovie.cshtml page originally had some CSS rules in it to define 
the look of validation error messages. Since you have a .css file for your site now, you can move 
those rules to the .css file. Remove them from the AddMovie.cshtml file and add them to the 
bottom of the Movies.css file. You are moving the following rules:  

.field-validation-error { 
  font-weight:bold; 
  color:red; 
  background-color:yellow; 
 } 
.validation-summary-errors{ 
  border:2px dashed red; 
  color:red; 
  background-color:yellow; 
  font-weight:bold; 
  margin:12px; 
} 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

112 

 
Now make the same sorts of changes in AddMovie.cshtml that you did for Movies.cshtml β€” add 
Layout="~/_Layout.cshtml; and remove the HTML markup that's now extraneous. Change the 
<h1> element to <h2>. When you're done, the page will look like this example: 

@{ 
    Layout = "~/_Layout.cshtml"; 
    Validation.RequireField("title", "You must enter a title"); 
    Validation.RequireField("genre", "Genre is required"); 
    Validation.RequireField("year", "You haven't entered a year"); 

    var title = ""; 
    var genre = ""; 
    var year = ""; 

    if(IsPost){ 
        if(Validation.IsValid()){ 
            title = Request.Form["title"]; 
            genre = Request.Form["genre"]; 
            year = Request.Form["year"]; 

            var db = Database.Open("WebPagesMovies"); 
            var insertCommand =  
                "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)"; 
            db.Execute(insertCommand, title, genre, year); 
            Response.Redirect("~/Movies"); 
        } 
    } 
} 
<h2>Add a Movie</h2> 
    @Html.ValidationSummary() 
<form method="post"> 
<fieldset> 
<legend>Movie Information</legend> 
<p><label for="title">Title:</label> 
<input type="text" name="title" value="@Request.Form["title"]" /> 
      @Html.ValidationMessage("title") 
</p> 

<p><label for="genre">Genre:</label> 
<input type="text" name="genre" value="@Request.Form["genre"]" /> 
      @Html.ValidationMessage("genre") 
</p> 

<p><label for="year">Year:</label> 
<input type="text" name="year" value="@Request.Form["year"]" /> 
      @Html.ValidationMessage("year") 
</p> 

<p><input type="submit" name="buttonSubmit" value="Add Movie" /></p> 
</fieldset> 
</form> 

Run the page. Now it looks like this illustration: 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

113 

 
 
 
 
 
 
You want to make similar changes to the pages in the site β€” EditMovie.cshtmland 
DeleteMovie.cshtml. However, before you do, you can make another change to the layout that 
makes it a little more flexible. 

Passing Title Information to the Layout Page 

The _Layout.cshtml page that you created has a <title> element that's set to "My Movie Site". 
Most browsers display the content of this element as the text on a tab: 

This title information is generic. Suppose that you want the title text to be more specific to the 
current page. (The title text is also used by search engines to determine what your page is about.) 
You can pass information from a content page like Movies.cshtml or AddMovie.cshtml to the 
layout page, and then use that information to customize what the layout page renders. 

Open the Movies.cshtml page again. In the code at the top, add the following line: 

Page.Title = "List Movies"; 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

114 

 
 
The Page object is available on all .cshtml pages and is for this purpose, namely to share 
information between a page and its layout.  

Open the _Layout.cshtml page. Change the <title> element so that it looks like this markup: 

<title>@Page.Title</title> 

This code renders whatever is in the Page.Title property right at that location in the page.  

Run the Movies.cshtml page. This time the browser tab shows what you passed as the value of 
Page.Title: 

If you want, view the page source in the browser. You can see that the <title> element is 
rendered as <title>List Movies</title>. 

The Page Object 

A useful feature of Page is that it's a dynamic object β€” the Title propertyis not a fixed or reserved 
name. You can use any name for a value of the Page object. For example, you could as easily have 
passed the title by using a property named Page.CurrentName or Page.MyPage. The only restriction 
is that the name has to follow the normal rules for what properties can be named. (For example, 
the name can't contain a space.) 

You can pass any number of values by using the Page object. If you wanted to pass movie 
information to the layout page, you could pass values by using something like Page.MovieTitle 
and Page.Genre and Page.MovieYear. (Or any other names that you invented to store the 
information.) The only requirement β€” which is probably obvious β€” is that you have to use the 
same names in the content page and the layout page. 

The information you pass by using the Page object isn't limited to just text to display on the layout 
page. You can pass a value to the layout page, and then code in the layout page can use the value 
to decide whether to display a section of the page, what .css file to use, and so on. The values you 
pass in the Page object are like any other values that you use in code. It's just that the values 
originate in the content page and are passed to the layout page. 

Open the AddMovie.cshtml page and add a line to the top of the code that provides a title for the 
AddMovie.cshtml page: 

Page.Title = "Add a Movie"; 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

115 

 
Run the AddMovie.cshtml page. You see the new title there: 

Updating the Remaining Pages to Use the Layout 

Now you can finish the remaining pages in your site so that they use the new layout. Open 
EditMovie.cshtml and DeleteMovie.cshtml in turn and make the same changes in each.  

Add the line of code that links to the layout page: 

Layout = "~/_Layout.cshtml"; 

Add a line to set the title of the page: 

Page.Title = "Edit a Movie"; 

or: 

Page.Title = "Delete a Movie"; 

Remove all the extraneous HTML markup β€” basically, leave only the bits that are inside the 
<body> element (plus the code block at the top). 

Change the <h1> element to be an <h2> element. 

When you've made these changes, test each and make sure thatit's displaying properly and that 
the title is correct. 

Parting Thoughts About Layout Pages 

In this tutorial you created a _Layout.cshtml page and used the RenderBody method to merge 
content from another page. That's the basic pattern for using layouts in Web Pages.  

Layout pages have additional features that we didn't cover here. For example, you can nest layout 
pages β€” one layout page can in turn reference another. Nested layouts can be useful if you're 
working with subsections of a site that require different layouts. You can also use additional 
methods (for example, RenderSection) to set up named sections in the layout page.  

The combination of layout pages and .css files is powerful. As you'll see in the next tutorial series, 
in WebMatrix you can create a site based on a template, which gives you a site that has prebuilt 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

116 

 
functionality in it. The templates make good use of layout pages and CSS to create sites that look 
great and that have features like menus. Here's a screenshot of the home page from a site based 
on a template, showing features that use layout pages and CSS: 

Coming Up Next 

In the next tutorial, you'll learn how to publish your site to the Internet so everyone can see it. 

Additional Resources 

β€’  Complete Listing for Movie Page (Updated to Use a Layout Page) 
β€’  Complete Page Listing for Add Movie Page (Updated for Layout) 
β€’  Complete Page Listing for Delete Movie Page (Updated for Layout) 
β€’  Complete Page Listing for Edit Movie Page (Updated for Layout) 
β€’  Creating a Consistent Look β€” An article that provides some more detail on working with 

layouts. It also describes how to pass a value to a layout page that shows or hides some of 
the content. 

β€’  Nested Layout Pages with Razor β€” Mike Brind blogs an example of how to nest layout 

pages. (Includes a download of the pages.) 

Introducing ASP.NET Web Pages 2 

Tutorial 8: Creating a Consistent Layout 

117 

 
 
 
Tutorial 9: Publishing a Site by Using WebMatrix 

What you'll learn: 

β€’  How to publish your site to the Internet. 
β€’  What's coming up in the next tutorial set. 

Publishing Your Site 

Up to now, you've done all your work on a local computer, including testing your pages. To run 
your .cshtml pages, you've used the web server that's built into WebMatrix, namely IIS Express. 
But of course no one can see the site you've created except you. To let others work with your site, 
you have to publish it to the Internet.  

Unless you have access to a public web server already, publishing means that you have to have an 
account with a hosting provider. A hosting provider is a company that owns publicly accessible 
web servers and that will rent you space for your site. Hosting plans run from a few dollars a 
month (or even free) for small sites to many hundreds of dollars a month for high-volume 
commercial websites. 

Note   You might have access to a public web server via the internet service provider (ISP) 
that you use to get internet service at home. However, your hosting provider must support 
ASP.NET Web Pages. Many ISPs don't, but it's always worth checking. 

In this tutorial, we'll give you an overview of how to publish. It's not practical to provide exact 
details for everything, because the process differs a bit for every hosting provider. But you'll get a 
good idea of how the process works.  

Selecting a hosting provider 

The first step is to find a hosting provider. You can look for one by searching the web or right from 
within WebMatrix. 

In the WebMatrix ribbon, click the Publish button. 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

118 

 
The Publish Settings dialog box is displayed. 

Click the Find web hosting link. 

You go to a page on the Microsoft site that lists hosting providers that support ASP.NET. 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

119 

 
 
Obviously, it can be difficult to know now exactly what hosting features you might require over 
the long term. Here are a couple of things to consider: 

β€’ 

For purposes of the WebPagesMovies site, you don't have to have a separate add-on for 
SQL Server, which often costs extra. In your site, you're using SQL Server Compact Edition, 
which is self-contained. However, you might need SQL Server access for some future 
website work you do. If you think you might, make sure that you can add SQL Server 
capability later. 

β€’  Check whether the hosting provider supports the Web Deploy publishing protocol. You 

can publish by using FTP protocol, but it's more convenient to use Web Deploy. 

Some sites offer a free trial period. A free trial is a good way to try publishing and hosting while 
you're still experimenting with WebMatrix and ASP.NET Web Pages. 

Pick one that you like.  For this tutorial, we selected DiscountASP.NET, because while we were 
creating the tutorial, that company had a promotion that let people host a site free for a few 
months.   

Note   Our choice of a hosting provider for this tutorial shouldn't be interpreted as an 
endorsement of that company over any other. But we had to pick one for illustration, and 
DiscountASP.NET is one of the many companies that supports ASP.NET Web Pages and the 
Web Deploy protocol for publishing. 

Typically, after you've signed up with the hosting provider, the company sends you an email that 
contains a user name and password, the URL of the web server, and so on. If the hosting company 
supports Web Deploy protocol, they might send you a file that contains publish settings, or let you 
download one. A publish settings file simplifies the process for you. 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

120 

 
Publishing the site 

When you've signed up and are ready to publish, click the Publish button in the WebMatrix 
ribbon. The Publish Settings dialog box is displayed. 

If the hosting provider sent you a publish settings file, click the Import publish settings link and 
import the file. If you don't have a publish settings file, fill in the fields by using the values that the 
hosting company sent you in email. Here's what the Publish Settings dialog box might look like 
when you're done: 

Click Validate Connection. If everything is ok, the dialog box reports Connected successfully, 
which means it can communicate with the hosting provider's server. 

If there's a problem, WebMatrix does its best to tell you what the problem is: 

Click Save to save your settings. WebMatrix offers to perform a test to make sure that it can 
communicate correctly with the hosting site: 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

121 

 
 
 
Click Yes. WebMatrix uploads some sample files to the hosting provider. When the compatibility 
test is done, WebMatrix reports the results: 

If you're ready to go, go ahead and click Continue to start the publish process for real. WebMatrix 
figures out what files are in your site and are already on the host server (right now, none) and 
gives you a preview of the publish process: 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

122 

 
 
The list of files to publish includes the web pages that you've created like Movies.cshtml. The list 
also includes files for helpers that you've installed, the files to run SQL Server Compact Edition for 
your database, and so on. As a result, the initial publish process can be substantial.  

Click Continue. WebMatrix copies your files to the hosting provider's server. When it's done, the 
results are reported in the status bar: 

To see your live site, click the link in the status bar. Add Movies to the URL, and you'll see the 
Movies.cshtml file that you created: 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

123 

 
 
 
Updating the live site: Republishing 

Once you've published your site, there are two copies of it β€” the version on your computer and 
the version on the hosting provider's server. You'll probably want to continue developing the site 
(if nothing else, as part of the next tutorial set).When you do, you have to republish your site in 
order to copy changes from your computer to the hosting provider's server. The publish process 
in WebMatrix can determine what files have changed on your site and publish just those files.  

To see how republishing works, open the Movies.cshtml site, make some small change, and then 
save the file. For example, change the title to Movies - Updated. 

Click the Publish button in the ribbon. WebMatrix determines what's changed and shows you a 
preview of the files it will publish. 

Important!By default, WebMatrix publishes your database (.sdf file) only the first time you 
publish the site. Once your site is published and people are interacting with the website, 
the database on the live site typically has the site's real data. You have to be very careful 
not to overwrite the live database with the .sdf file that's on your computer, which usually 
contains only test data. That's why you see the warning Publishing will overwrite any 
remote databases, and why the check box for WebPagesMovies.sdf is cleared by default. 

Click Continue. WebMatrix publishes the changed files and shows you a success message, like it 
did the first time you published. 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

124 

 
Goto the live site (you can click the link in the success message if it's still showing) and verify that 
your change has been published. 

Editing files remotely 

As an alternative to changing your site and then republishing, you can edit remote files directly in 
WebMatrix. In this scenario, you open a file that's on the hosting provider's server, and 
WebMatrix downloads a copy of it for you to edit. Every time you save the file, WebMatrix sends 
the changes to the hosting site.  

Remote editing is an easy way to make changes to your live site. However, the changes you make 
this way aren't synchronized with the files in your local site. To synchronize the local files with the 
remote site, you can download the remote files. This process works much like publishing, except 
in reverse. 

We won't describe more about the remote-editing and remote-download facilities of WebMatrix 
here. They're quite useful if multiple people have to work on the same site on different 
computers. For more information, see Publish and Edit a Remote Site with WebMatrix 2. 

Preview of the Next Tutorial Set 

In this tutorial you've created a site that's functional and that illustrates much of the functionality 
of ASP.NET Web Pages. But there's plenty more to learn. The next tutorial set continues with your 
Movies site and teaches you the following: 

β€’  How to start a site from a template, which instantly gives you a professional layout plus 

built-in functionality for common tasks. 

β€’  More about how to work with forms β€” radio buttons, checkboxes, drop-down lists, etc. 
β€’  How to perform more sophisticated database searches. 
β€’  How to add social media to your site β€” for example, adding a Facebook "Like" button. 
β€’  How to begin adding client-side functionality to your site (by using jQuery), which gives 

the user a very responsive experience. 

β€’  How to add images to the site, including images uploaded by users. 
β€’  How to send email from your site. 
β€’  How to add login security to your site, so that some functions (like deleting a movie) are 

available only to users who've been authorized. 

Additional Resources 

β€’  ASP.NET WebMatrix ASP.NET Web Pages forum, a great place to post questions and get 

answers. 

β€’  How to publish a web application using WebMatrix, an end-to-end tutorial about how to 

find a hosting provider and publish to the Internet. 

Introducing ASP.NET Web Pages 2 

Tutorial 9: Publishing a Site by Using WebMatrix 

125 

This page intentionally left blank 

Appendix: Code Listings 

This appendix lists the finished versions of all the pages that you create in this tutorial set. 

Complete Listing for TestRazor Page 

@{ 

   // Working with numbers 

   var a = 4; 

   var b = 5; 

   var theSum = a + b; 

   // Working with characters (strings) 

   var technology = "ASP.NET"; 

   var product ="Web Pages"; 

   // Working with objects 

   var rightNow = DateTime.Now; 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<title>Testing Razor Syntax</title> 

<meta charset="utf-8" /> 

<style> 

    body {font-family:Verdana; margin-left:50px; margin-top:50px;} 

    div {border: 1px solid black; width:50%; margin:1.2em;padding:1em;} 

    span.bright {color:red;} 

</style> 

</head> 

<body> 

<h1>Testing Razor Syntax</h1> 

<form method="post"> 

<div> 

<p>The value of <em>a</em> is @a.  The value of <em>b</em> is @b.  

<p>The sum of <em>a</em> and <em>b</em> is <strong>@theSum</strong>.</p> 

<p>The product of <em>a</em> and <em>b</em> is <strong>@(a*b)</strong>.</p> 

</div> 

<div> 

<p>The technology is @technology, and the product is @product.</p> 

<p>Together they are <span class="bright">@(technology + " " + product)</span></p> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

127 

 
 
 
 
 
</div> 

<div> 

<p>The current date and time is: @rightNow</p> 

<p>The URL of the current page is<br/><br/><code>@Request.Url</code></p> 

</div> 

</form> 

</body> 

</html> 

Complete Listing for TestRazorPart2 Page 

@{ 

   var message = "This is the first time you've requested the page."; 

   if(IsPost){ 

      message = "Now you've submitted the page."; 

   } 

   var showMessage = false; 

   if(Request.QueryString["show"].AsBool() == true){ 

     showMessage = true; 

   } 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<title>Testing Razor Syntax - Part 2</title> 

<meta charset="utf-8" /> 

<style> 

      body {font-family:Verdana; margin-left:50px; margin-top:50px;} 

      div {border: 1px solid black; width:50%; margin:1.2em;padding:1em;} 

</style> 

</head> 

<body> 

<h1>Testing Razor Syntax - Part 2</h1> 

<form method="post"> 

<div> 

<!--<p>@message</p>--> 

      @if(showMessage){ 

<p>@message</p> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

128 

 
 
 
 
 
      }  

<p><input type="submit" value="Submit" /></p> 

      @if(IsPost){ 

<p>You submitted the page at @DateTime.Now</p> 

      } 

</div> 

</form> 

</body> 

</html> 

Complete Listing for TwitterTest Page 

@{ 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<meta charset="utf-8" /> 

<title></title> 

</head> 

<body> 

<div> 

        @TwitterGoodies.Search("webmatrix") 

</div> 

<div> 

        @TwitterGoodies.FollowButton("microsoft") 

</div> 

</body> 

</html> 

Complete Listing for Movies Page 

@{ 

    var db = Database.Open("WebPagesMovies"); 

    var selectedData = db.Query("SELECT * FROM Movies"); 

    var grid = new WebGrid(source: selectedData, rowsPerPage: 3); 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

129 

 
 
 
<meta charset="utf-8" /> 

<title>Movies</title> 

<style type="text/css"> 

          .grid { margin: 4px; border-collapse: collapse; width: 600px; } 

          .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 

          .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 

          .alt { background-color: #E8E8E8; color: #000; } 

</style> 

</head> 

<body> 

<h1>Movies</h1> 

<div> 

            @grid.GetHtml( 

                tableStyle: "grid", 

                headerStyle: "head", 

                alternatingRowStyle: "alt", 

                columns: grid.Columns( 

                    grid.Column("Title"), 

                    grid.Column("Genre"), 

                    grid.Column("Year") 

                ) 

            ) 

</div> 

</body> 

</html> 

Complete Listing for Movie Page (Updated with Search) 

@{ 

    var db = Database.Open("WebPagesMovies") ; 

    var selectCommand = "SELECT * FROM Movies"; 

    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 

        searchTerm = Request.QueryString["searchGenre"]; 

    } 

    if(!Request.QueryString["searchTitle"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 

        searchTerm = "%" + Request["searchTitle"] + "%";  

    } 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

130 

 
 
 
    var selectedData = db.Query(selectCommand, searchTerm); 

    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  

        rowsPerPage:3); 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<meta charset="utf-8" /> 

<title>Movies</title> 

<style type="text/css"> 

      .grid { margin: 4px; border-collapse: collapse; width: 600px; } 

      .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 

      .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 

      .alt { background-color: #E8E8E8; color: #000; } 

</style> 

</head> 

<body> 

<h1>Movies</h1> 

<form method="get"> 

<div> 

<label for="searchGenre">Genre to look for:</label> 

<input type="text" name="searchGenre"  

            value="@Request.QueryString["searchGenre"]" /> 

<input type="Submit" value="Search Genre" /><br/> 

        (Leave blank to list all movies.)<br/> 

</div> 

<div> 

<label for="SearchTitle">Movie title contains the following:</label> 

<input type="text" name="searchTitle"  

              value="@Request.QueryString["searchTitle"]" /> 

<input type="Submit" value="Search Title" /><br/> 

</div> 

</form> 

<div> 

      @grid.GetHtml( 

        tableStyle: "grid", 

        headerStyle: "head", 

        alternatingRowStyle: "alt", 

        columns: grid.Columns( 

          grid.Column("Title"), 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

131 

 
 
 
 
          grid.Column("Genre"), 

          grid.Column("Year") 

        ) 

      ) 

</div> 

</body> 

</html> 

Complete Listing for AddMovie Page 

@{ 

    Validation.RequireField("title", "You must enter a title"); 

    Validation.RequireField("genre", "Genre is required"); 

    Validation.RequireField("year", "You haven't entered a year"); 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    if(IsPost && Validation.IsValid()){ 

       title = Request.Form["title"]; 

       genre = Request.Form["genre"]; 

       year = Request.Form["year"]; 

       var db = Database.Open("WebPagesMovies"); 

       var insertCommand = "INSERT INTO Movies (Title, Genre, Year) " +  

           " Values(@0, @1, @2)"; 

       db.Execute(insertCommand, title, genre, year); 

       Response.Redirect("~/Movies"); 

    } 

} 

<!DOCTYPE html> 

<html> 

<head> 

<meta charset="utf-8" /> 

<title>Add a Movie</title> 

<style type="text/css"> 

    .field-validation-error { 

      font-weight:bold; 

      color:red; 

      background-color:yellow; 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

132 

 
 
 
 
 
     } 

    .validation-summary-errors{ 

      border:2px dashed red; 

      color:red; 

      background-color:yellow; 

      font-weight:bold; 

      margin:12px; 

    } 

</style> 

</head> 

<body> 

<h1>Add a Movie</h1> 

  @Html.ValidationSummary() 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><label for="title">Title:</label> 

<input type="text" name="title" value="@Request.Form["title"]" /> 

          @Html.ValidationMessage("title") 

<p><label for="genre">Genre:</label> 

<input type="text" name="genre" value="@Request.Form["genre"]" /> 

         @Html.ValidationMessage("genre") 

<p><label for="year">Year:</label> 

<input type="text" name="year" value="@Request.Form["year"]" /> 

          @Html.ValidationMessage("year") 

<p><input type="submit" name="buttonSubmit" value="Add Movie" /></p> 

</fieldset> 

</form> 

</body> 

</html> 

Complete Listing for Movie Page (Updated with Edit Links) 

@{ 

    var db = Database.Open("WebPagesMovies") ; 

    var selectCommand = "SELECT * FROM Movies"; 

    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

133 

 
 
 
 
        searchTerm = Request.QueryString["searchGenre"]; 

    } 

    if(!Request.QueryString["searchTitle"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 

        searchTerm = "%" + Request.QueryString["searchTitle"] + "%";  

    } 

    var selectedData = db.Query(selectCommand, searchTerm); 

    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  

        rowsPerPage:3); 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<meta charset="utf-8" /> 

<title>Movies</title> 

<style type="text/css"> 

          .grid { margin: 4px; border-collapse: collapse; width: 600px; } 

          .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 

          .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 

          .alt { background-color: #E8E8E8; color: #000; } 

</style> 

</head> 

<body> 

<h1>Movies</h1> 

<form method="get"> 

<div> 

<label for="searchGenre">Genre to look for:</label> 

<input type="text" name="searchGenre"  

value="@Request.QueryString["searchGenre"]" /> 

<input type="Submit" value="Search Genre" /><br/> 

                (Leave blank to list all movies.)<br/> 

</div> 

<div> 

<label for="SearchTitle">Movie title contains the  

following:</label> 

<input type="text" name="searchTitle"  

value="@Request.QueryString["searchTitle"]" /> 

<input type="Submit" value="Search Title" /><br/> 

</div> 

</form> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

134 

 
 
 
 
<div> 

             @grid.GetHtml( 

                tableStyle: "grid", 

                headerStyle: "head", 

                alternatingRowStyle: "alt", 

                columns: grid.Columns( 

                    grid.Column(format:  

@<a href="~/[email protected]">Edit</a>), 

                    grid.Column("Title"), 

                    grid.Column("Genre"), 

                    grid.Column("Year") 

                ) 

            )  

</div> 

<p> 

<a href="~/AddMovie">Add a movie</a> 

</p> 

</body> 

</html> 

Complete Page Listing for Edit Movie Page 

@{ 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    var movieId = ""; 

    if(!IsPost){ 

        //if(!Request.QueryString["ID"].IsEmpty()){ 

        if(!Request.QueryString["ID"].IsEmpty() && 

                Request.QueryString["ID"].IsInt()) { 

            movieId = Request.QueryString["ID"]; 

            var db = Database.Open("WebPagesMovies"); 

            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 

            var row = db.QuerySingle(dbCommand, movieId); 

            if(row != null) { 

                title = row.Title; 

                genre = row.Genre; 

                year = row.Year; 

            } 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

135 

 
 
 
            else{ 

                Validation.AddFormError("No movie was selected."); 

                // Use the following line instead for versions of ASP.NET  

                // Web Pages 2 earlier than the RC release. 

                //ModelState.AddFormError("No movie was selected."); 

            } 

        }     

        else{ 

            Validation.AddFormError("No movie was selected."); 

            // Use the following line instead for versions of ASP.NET  

            // Web Pages 2 earlierthan the RC release. 

            //ModelState.AddFormError("No movie was selected."); 

        }     

    } 

    if(IsPost){ 

        Validation.RequireField("title", "You must enter a title"); 

        Validation.RequireField("genre", "Genre is required"); 

        Validation.RequireField("year", "You haven't entered a year"); 

        Validation.RequireField("movieid", "No movie ID was submitted!"); 

        title = Request.Form["title"]; 

        genre = Request.Form["genre"]; 

        year = Request.Form["year"]; 

        movieId = Request.Form["movieId"]; 

        if(Validation.IsValid()){     

            var db = Database.Open("WebPagesMovies"); 

            var updateCommand = "UPDATE Movies " +  

                  " SET Title=@0, Genre=@1, Year=@2 WHERE Id=@3"; 

            db.Execute(updateCommand, title, genre, year, movieId); 

            Response.Redirect("~/Movies"); 

        } 

    } 

}  

<!DOCTYPE html> 

<html> 

<head> 

<meta charset="utf-8" /> 

<title>Edit a Movie</title> 

<style> 

      .validation-summary-errors{ 

        border:2px dashed red; 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

136 

 
 
 
 
        color:red; 

        font-weight:bold; 

        margin:12px; 

      } 

</style> 

</head> 

</head> 

<body> 

<h1>Edit a Movie</h1> 

    @Html.ValidationSummary() 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><label for="title">Title:</label> 

<input type="text" name="title" value="@title" /></p> 

<p><label for="genre">Genre:</label> 

<input type="text" name="genre" value="@genre" /></p> 

<p><label for="year">Year:</label> 

<input type="text" name="year" value="@year" /></p> 

<input type="hidden" name="movieid" value="@movieId" /> 

<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p> 

</fieldset> 

</form> 

<p><a href="~/Movies">Return to movie listing</a></p> 

</body> 

</html> 

Complete Listing for Movie Page (Updated with Delete Links) 

@{ 

    var db = Database.Open("WebPagesMovies") ; 

    var selectCommand = "SELECT * FROM Movies"; 

    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 

        searchTerm = Request.QueryString["searchGenre"]; 

    } 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

137 

 
 
 
 
 
    
    if(!Request.QueryString["searchTitle"].IsEmpty() ) {  

      selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 

      searchTerm = "%" + Request.QueryString["searchTitle"] + "%";  

    } 

    var selectedData = db.Query(selectCommand, searchTerm); 

    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  

        rowsPerPage:3); 

} 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<meta charset="utf-8" /> 

<title>Movies</title> 

<style type="text/css"> 

        .grid { margin: 4px; border-collapse: collapse; width: 600px; } 

        .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 

        .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 

        .alt { background-color: #E8E8E8; color: #000; } 

</style>       

</head> 

<body> 

<h1>Movies</h1> 

<form method="get"> 

<div> 

<label for="searchGenre">Genre to look for:</label> 

<input type="text" name="searchGenre"  

              value="@Request.QueryString["searchGenre"]" /> 

<input type="Submit" value="Search Genre" /><br/> 

          (Leave blank to list all movies.)<br/> 

</div> 

<div> 

<label for="SearchTitle">Movie title contains the following:</label> 

<input type="text" name="searchTitle"  

               value="@Request.QueryString["searchTitle"]" /> 

<input type="Submit" value="Search Title" /><br/> 

</div> 

</form> 

<div> 

          @grid.GetHtml( 

            tableStyle: "grid", 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

138 

 
 
         
         
            headerStyle: "head", 

            alternatingRowStyle: "alt", 

            columns: grid.Columns( 

                grid.Column(format: @<a href="~/[email protected]">Edit</a>), 

                grid.Column("Title"), 

                grid.Column("Genre"), 

                grid.Column("Year"), 

                grid.Column(format:  

                   @<a href="~/[email protected]">Delete</a>) 

            ) 

        ) 

</div> 

<p> 

<a href="~/AddMovie">Add a movie</a> 

</p> 

</body> 

</html> 

Complete Listing for DeleteMovie Page 

@{ 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    var movieId = ""; 

    if(!IsPost){ 

        if(!Request.QueryString["ID"].IsEmpty() && 

                Request.QueryString["ID"].IsInt()){ 

            movieId = Request.QueryString["ID"]; 

            var db = Database.Open("WebPagesMovies"); 

            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 

            var row = db.QuerySingle(dbCommand, movieId); 

            if(row != null) { 

                title = row.Title; 

                genre = row.Genre; 

                year = row.Year; 

            } 

            else{ 

                Validation.AddFormError("No movie was found for that ID."); 

                // If you are using a version of ASP.NET Web Pages 2 that's  

                // earlier than the RC release, comment out the preceding  

                // statement and uncomment the following one. 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

139 

 
                //ModelState.AddFormError("No movie was found for that ID."); 

            } 

        } 

        else{ 

            Validation.AddFormError("No movie was found for that ID."); 

            // If you are using a version of ASP.NET Web Pages 2 that's  

            // earlier than the RC release, comment out the preceding  

            // statement and uncomment the following one. 

            //ModelState.AddFormError("No movie was found for that ID."); 

        }     

    } 

    if(IsPost && !Request["buttonDelete"].IsEmpty()){ 

        movieId = Request.Form["movieId"]; 

        var db = Database.Open("WebPagesMovies"); 

        var deleteCommand = "DELETE FROM Movies WHERE ID = @0"; 

        db.Execute(deleteCommand, movieId); 

        Response.Redirect("~/Movies"); 

    } 

} 

<html> 

<head> 

<title>Delete a Movie</title> 

</head> 

<body> 

<h1>Delete a Movie</h1> 

        @Html.ValidationSummary() 

<p><a href="~/Movies">Return to movie listing</a></p> 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><span>Title:</span> 

         <span>@title</span></p> 

<p><span>Genre:</span> 

         <span>@genre</span></p> 

<p><span>Year:</span> 

<span>@year</span></p> 

<input type="hidden" name="movieid" value="@movieId" /> 

<p><input type="submit" name="buttonDelete" value="Delete Movie" /></p> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

140 

     
 
 
       
       
 
</fieldset> 

<p><a href="~/Movies">Return to movie listing</a></p> 

</form>  

</body> 

</html> 

Complete Listing for Movie Page (Updated to Use a Layout Page) 

@{ 

    Layout = "~/_Layout.cshtml"; 

    Page.Title = "List Movies"; 

    var db = Database.Open("WebPagesMovies") ; 

    var selectCommand = "SELECT * FROM Movies"; 

    var searchTerm = ""; 

    if(!Request.QueryString["searchGenre"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Genre = @0"; 

        searchTerm = Request.QueryString["searchGenre"]; 

    } 

    if(!Request.QueryString["searchTitle"].IsEmpty() ) {  

        selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0"; 

        searchTerm = "%" + Request.QueryString["searchTitle"] + "%";  

    } 

    var selectedData = db.Query(selectCommand, searchTerm); 

    var grid = new WebGrid(source: selectedData, defaultSort: "Genre",  

        rowsPerPage:3); 

} 

<h2>List Movies</h2> 

<form method="get"> 

<div> 

<label for="searchGenre">Genre to look for:</label> 

<input type="text" name="searchGenre"  

            value="@Request.QueryString["searchGenre"]" /> 

<input type="Submit" value="Search Genre" /><br/> 

        (Leave blank to list all movies.)<br/> 

</div> 

<div> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

141 

 
 
 
 
 
 
 
<label for="SearchTitle">Movie title contains the following:</label> 

<input type="text" name="searchTitle"  

           value="@Request.QueryString["searchTitle"]" /> 

<input type="Submit" value="Search Title" /><br/> 

</div> 

</form> 

<div> 

    @grid.GetHtml( 

        tableStyle: "grid", 

        headerStyle: "head", 

        alternatingRowStyle: "alt", 

        columns: grid.Columns( 

    grid.Column(format: @<a href="~/[email protected]">Edit</a>), 

    grid.Column("Title"), 

    grid.Column("Genre"), 

    grid.Column("Year"), 

    grid.Column(format: @<a href="~/[email protected]">Delete</a>) 

        ) 

    ) 

</div> 

<p><a href="~/AddMovie">Add a movie</a></p> 

Complete Page Listing for Add Movie Page (Updated for Layout) 

@{ 

    Layout = "~/_Layout.cshtml"; 

    Page.Title = "Add a Movie"; 

    Validation.RequireField("title", "You must enter a title"); 

    Validation.RequireField("genre", "Genre is required"); 

    Validation.RequireField("year", "You haven't entered a year"); 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    if(IsPost){ 

        if(Validation.IsValid()){ 

            title = Request.Form["title"]; 

            genre = Request.Form["genre"]; 

            year = Request.Form["year"]; 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

142 

 
 
 
 
 
 
 
 
 
 
            var db = Database.Open("WebPagesMovies"); 

            var insertCommand = "INSERT INTO Movies (Title, Genre, Year) " +  

                 " VALUES(@0, @1, @2)"; 

            db.Execute(insertCommand, title, genre, year); 

            Response.Redirect("~/Movies"); 

        } 

    } 

} 

<h2>Add a Movie</h2> 

@Html.ValidationSummary() 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><label for="title">Title:</label> 

<input type="text" name="title" value="@Request.Form["title"]" /> 

        @Html.ValidationMessage("title") 

<p><label for="genre">Genre:</label> 

<input type="text" name="genre" value="@Request.Form["genre"]" /> 

        @Html.ValidationMessage("genre") 

<p><label for="year">Year:</label> 

<input type="text" name="year" value="@Request.Form["year"]" /> 

        @Html.ValidationMessage("year") 

<p><input type="submit" name="buttonSubmit" value="Add Movie" /></p> 

</fieldset> 

</form> 

Complete Page Listing for Delete Movie Page (Updated for Layout) 

@{ 

    Layout = "~/_Layout.cshtml"; 

    Page.Title = "Delete a Movie"; 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    var movieId = ""; 

    if(!IsPost){ 

        if(!Request.QueryString["ID"].IsEmpty() && 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

143 

 
 
 
 
 
 
                Request.QueryString["ID"].AsInt() > 0){ 

            movieId = Request.QueryString["ID"]; 

            var db = Database.Open("WebPagesMovies"); 

            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 

            var row = db.QuerySingle(dbCommand, movieId); 

            if(row != null) { 

                title = row.Title; 

                genre = row.Genre; 

                year = row.Year; 

            } 

            else{ 

                Validation.AddFormError("No movie was found for that ID."); 

                // If you are using a version of ASP.NET Web Pages 2 that's  

                // earlier than the RC release, comment out the preceding  

                // statement and uncomment the following one. 

                //ModelState.AddFormError("No movie was found for that ID."); 

            } 

        } 

        else{ 

            Validation.AddFormError("No movie was found for that ID."); 

            // If you are using a version of ASP.NET Web Pages 2 that's  

            // earlier than the RC release, comment out the preceding  

            // statement and uncomment the following one. 

            //ModelState.AddFormError("No movie was found for that ID."); 

        }     

    } 

    if(IsPost && !Request["buttonDelete"].IsEmpty()){ 

        movieId = Request.Form["movieId"]; 

        var db = Database.Open("WebPagesMovies"); 

        var deleteCommand = "DELETE FROM Movies WHERE ID = @0"; 

        db.Execute(deleteCommand, movieId); 

        Response.Redirect("~/Movies"); 

    } 

} 

<h2>Delete a Movie</h2> 

@Html.ValidationSummary() 

<p><a href="~/Movies">Return to movie listing</a></p> 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><span>Title:</span> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

144 

 
 
 
<span>@title</span></p> 

<p><span>Genre:</span> 

<span>@genre</span></p> 

<p><span>Year:</span> 

<span>@year</span></p> 

<input type="hidden" name="movieid" value="@movieId" /> 

<p><input type="submit" name="buttonDelete" value="Delete Movie" /></p> 

</fieldset> 

</form> 

Complete Page Listing for Edit Movie Page (Updated for Layout) 

@{ 

    Layout = "~/_Layout.cshtml"; 

    Page.Title = "Edit a Movie"; 

    var title = ""; 

    var genre = ""; 

    var year = ""; 

    var movieId = ""; 

    if(!IsPost){ 

        if(!Request.QueryString["ID"].IsEmpty() && 

Request.QueryString["ID"].IsInt()) { 

            movieId = Request.QueryString["ID"]; 

            var db = Database.Open("WebPagesMovies"); 

            var dbCommand = "SELECT * FROM Movies WHERE ID = @0"; 

            var row = db.QuerySingle(dbCommand, movieId); 

            if(row != null) { 

                title = row.Title; 

                genre = row.Genre; 

                year = row.Year; 

            } 

            else{ 

                Validation.AddFormError("No movie was selected."); 

                // If you are using a version of ASP.NET Web Pages 2 that's  

                // earlier than the RC release, comment out the preceding  

                // statement and uncomment the following one. 

                //ModelState.AddFormError("No movie was selected."); 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

145 

 
 
 
 
 
 
            } 

        }     

        else{ 

            Validation.AddFormError("No movie was selected."); 

            // If you are using a version of ASP.NET Web Pages 2 that's  

            // earlier than the RC release, comment out the preceding  

            // statement and uncomment the following one. 

            //ModelState.AddFormError("No movie was selected."); 

        }     

    } 

    if(IsPost){ 

        Validation.RequireField("title", "You must enter a title"); 

        Validation.RequireField("genre", "Genre is required"); 

        Validation.RequireField("year", "You haven't entered a year"); 

        Validation.RequireField("movieid", "No movie ID was submitted!"); 

        title = Request.Form["title"]; 

        genre = Request.Form["genre"]; 

        year = Request.Form["year"]; 

        movieId = Request.Form["movieId"]; 

        if(Validation.IsValid()){     

            var db = Database.Open("WebPagesMovies"); 

            var updateCommand = "UPDATE Movies " +  

                 " SET Title=@0, Genre=@1, Year=@2 WHERE Id=@3"; 

            db.Execute(updateCommand, title, genre, year, movieId); 

            Response.Redirect("~/Movies"); 

        } 

    } 

}  

<h2>Edit a Movie</h2> 

@Html.ValidationSummary() 

<form method="post"> 

<fieldset> 

<legend>Movie Information</legend> 

<p><label for="title">Title:</label> 

<input type="text" name="title" value="@title" /></p> 

<p><label for="genre">Genre:</label> 

<input type="text" name="genre" value="@genre" /></p> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

146 

 
 
 
 
 
 
 
<p><label for="year">Year:</label> 

<input type="text" name="year" value="@year" /></p> 

<input type="hidden" name="movieid" value="@movieId" /> 

<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p> 

</fieldset> 

</form> 

<p><a href="~/Movies">Return to movie listing</a></p> 

Introducing ASP.NET Web Pages 2 

Appendix: Code Listings 

147