ASP.NET
MVC
The MVC Programming Model
MVC is one of three ASP.NET programming models.MVC is a framework for building web applications using a MVC (Model View Controller) design:
- The Model represents the application core (for instance a list of database records).
- The View displays the data (the database records).
- The Controller handles the
input (to the database records).
|
The MVC model defines web
applications with 3 logic layers:
The business layer (Model logic)
The display layer (View logic)
The input control (Controller logic) |
Often model objects retrieve data (and store data) from a database.
The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.
Web Forms vs MVC
The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.Visual Studio Express 2012/2010
Visual Studio Express is a free version of Microsoft Visual Studio.Visual Studio Express is a development tool tailor made for MVC (and Web Forms).
Visual Studio Express contains:
- MVC and Web Forms
- Drag-and-drop web controls and web components
- A web server language (Razor using VB or C#)
- A web server (IIS Express)
- A database server (SQL Server Compact)
- A full web development framework (ASP.NET)
ASP.NET MVC - Internet Application
To learn ASP.NET MVC, we will Build an Internet ApplicationPart I: Creating the Application
What We Will Build
We will build an Internet application that supports adding, editing, deleting, and listing of information stored in a database.What We Will Do
Visual Web Developer offers different templates for building web applications.We will use Visual Web Developer to create an empty MVC Internet application with HTML5 markup.
When the empty Internet application is created, we will gradually add code to the application until it is fully finished. We will use C# as the programming language, and the newest Razor server code markup.
Along the way we will explain the content, the code, and all the components of the application.
Creating the Web Application
If you have Visual Web Developer installed, start Visual Web Developer and select New Project. Otherwise just read and learn.In the New Project dialog box:
- Open the Visual C# templates
- Select the template ASP.NET MVC 3 Web Application
- Set the project name to MvcDemo
- Set the disk location to something like c:\w3schools_demo
- Click OK
- Select the Internet Application template
- Select the Razor Engine
- Select HTML5 Markup
- Click OK
We will explore the content of the files and folders in the next chapter of this tutorial.
ASP.NET MVC - Application Folders
To learn ASP.NET MVC, we are Building an Internet applicationPart II: Exploring the Application Folders
MVC Folders
A typical ASP.NET MVC web application has the following folder content:
|
|
Application
information
Properties
References
Application
folders
App_Data
Folder
Content Folder Controllers Folder Models Folder Scripts Folder Views Folder
Configuration
files
Global.asax
packages.config Web.config |
Standard naming reduces the amount of code, and makes it easier for developers to understand MVC projects.
Below is a brief summary of the content of each folder:
The App_Data Folder
The App_Data folder is for storing application data.We will add an SQL database to the App_Data folder, later in this tutorial.
The Content Folder
The Content folder is used for static files like style sheets (css files), icons and images.Visual Web Developer automatically adds a themes folder to the Content folder. The themes folder is filled with jQuery styles and pictures. In this project you can delete the themes folder.
Visual Web Developer also adds a standard style sheet file to the project: the file Site.css in the content folder. The style sheet file is the file to edit when you want to change the style of the application.
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.
The Controllers Folder
The Controllers folder contains the controller classes responsible for handling user input and responses.MVC requires the name of all controller files to end with "Controller".
Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):
We will create more controllers later in this tutorial.
The Models Folder
The Models folder contains the classes that represent the application models. Models hold and manipulate application data.We will create models (classes) in a later chapter of this tutorial.
The Views Folder
The Views folder stores the HTML files related to the display of the application (the user interfaces).The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout pages).
We will edit the layout files in the next chapter of this tutorial.
The Scripts Folder
The Scripts folder stores the JavaScript files of the application.By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.
ASP.NET MVC - Styles and Layout
To learn ASP.NET MVC, we are Building an Internet Application.Part III: Adding Styles and a Consistent Look (Layout).
Adding a Layout
The file _Layout.cshtml represent the layout of each page in the application. It is located in the Shared folder inside the Views folder.Open the file and swap the content with this:
eg.
<!DOCTYPE
html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></script>
</head>
<body>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Movies", "Index", "Movies")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
<section id="main">
@RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
</body>
</html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></script>
</head>
<body>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Movies", "Index", "Movies")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
<section id="main">
@RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
</body>
</html>
HTML Helpers
In the code above, HTML helpers are used to modify HTML output:@Url.Content() - URL content will be inserted here.
@Html.ActionLink() - HTML link will be inserted here.
Razor Syntax
In the code above, the code marked red are C# using Razor markup.@ViewBag.Title - The page title will be inserted here.
@RenderBody() - The page content will be rendered here.
Adding Styles
The style sheet for the application is called Site.css. It is located in the Content folder.Open the file Site.css and swap the content with this:
eg.
body
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
border-bottom: 3px solid #cc9900;
font: Georgia, serif;
color: #996600;
}
#main
{
padding: 20px;
background-color: #ffffff;
border-radius: 0 4px 4px 4px;
}
a
{
color: #034af3;
}
/* Menu Styles ------------------------------*/
ul#menu
{
padding: 0px;
position: relative;
margin: 0;
}
ul#menu li
{
display: inline;
}
ul#menu li a
{
background-color: #e8eef4;
padding: 10px 20px;
text-decoration: none;
line-height: 2.8em;
/*CSS3 properties*/
border-radius: 4px 4px 0 0;
}
ul#menu li a:hover
{
background-color: #ffffff;
}
/* Forms Styles ------------------------------*/
fieldset
{
padding-left: 12px;
}
fieldset label
{
display: block;
padding: 4px;
}
input[type="text"], input[type="password"]
{
width: 300px;
}
input[type="submit"]
{
padding: 4px;
}
/* Data Styles ------------------------------*/
table.data
{
background-color:#ffffff;
border:1px solid #c3c3c3;
border-collapse:collapse;
width:100%;
}
table.data th
{
background-color:#e8eef4;
border:1px solid #c3c3c3;
padding:3px;
}
table.data td
{
border:1px solid #c3c3c3;
padding:3px;
}
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
border-bottom: 3px solid #cc9900;
font: Georgia, serif;
color: #996600;
}
#main
{
padding: 20px;
background-color: #ffffff;
border-radius: 0 4px 4px 4px;
}
a
{
color: #034af3;
}
/* Menu Styles ------------------------------*/
ul#menu
{
padding: 0px;
position: relative;
margin: 0;
}
ul#menu li
{
display: inline;
}
ul#menu li a
{
background-color: #e8eef4;
padding: 10px 20px;
text-decoration: none;
line-height: 2.8em;
/*CSS3 properties*/
border-radius: 4px 4px 0 0;
}
ul#menu li a:hover
{
background-color: #ffffff;
}
/* Forms Styles ------------------------------*/
fieldset
{
padding-left: 12px;
}
fieldset label
{
display: block;
padding: 4px;
}
input[type="text"], input[type="password"]
{
width: 300px;
}
input[type="submit"]
{
padding: 4px;
}
/* Data Styles ------------------------------*/
table.data
{
background-color:#ffffff;
border:1px solid #c3c3c3;
border-collapse:collapse;
width:100%;
}
table.data th
{
background-color:#e8eef4;
border:1px solid #c3c3c3;
padding:3px;
}
table.data td
{
border:1px solid #c3c3c3;
padding:3px;
}
x
The _ViewStart File
The _ViewStart file in the Shared folder (inside the Views folder) contains the following content:
@{Layout
= "~/Views/Shared/_Layout.cshtml";}
If you remove this file, you must add this line to all views.
ASP.NET MVC - Controllers
To learn ASP.NET MVC, we are Building an Internet Application.Part IV: Adding a Controller.
The Controllers Folder
The Controllers Folder contains the controller classes responsible for handling user input and responses.
MVC
requires the name of all controllers to end with "Controller".
In our example, Visual Web Developer has created the following
files: HomeController.cs (for the Home and About
pages) and AccountController.cs (For the Log On
pages):Web servers will normally map incoming URL requests directly to disk files on the server. For example: a URL request like "http://www.w3schools.com/default.asp" will map directly to the file "default.asp" at the root directory of the server.
The MVC framework maps differently. MVC maps URLs to methods. These methods are in classes called "Controllers".
Controllers are responsible for processing incoming requests, handling input, saving data, and sending a response to send back to the client.
The Home controller
The controller file in our application HomeController.cs, defines the two controls Index and About.Swap the content of the HomeController.cs file with this:
using
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}
public ActionResult About()
{return View();}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}
public ActionResult About()
{return View();}
}
}
The Controller Views
The files Index.cshtml and About.cshtml in the Views folder defines the ActionResult views Index() and About() in the controller.ASP.NET MVC - Views
To learn ASP.NET MVC, we are Building an Internet Application.Part V: Adding Views for Displaying the Application.
The Views Folder
The Views folder stores the files (HTML files) related to the display of the application (the user interfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending on the language content.The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout pages).
ASP.NET File Types
The following HTML file types can be found in the Views Folder:
File Type |
Extention |
---|---|
Plain HTML |
.htm or .html |
Classic ASP |
.asp |
Classic ASP.NET |
.aspx |
ASP.NET Razor C# |
.cshtml |
ASP.NET Razor VB |
.vbhtml |
The Index File
The file Index.cshtml represents the Home page of the application. It is the application's default file (index file).Put the following content in the file:
@{ViewBag.Title
= "Home Page";}
<h1>Welcome to W3Schools</h1>
<p>Put Home Page content here</p>
<h1>Welcome to W3Schools</h1>
<p>Put Home Page content here</p>
The About File
The file About.cshtml represent the About page of the application.Put the following content in the file:
@{ViewBag.Title
= "About Us";}
<h1>About Us</h1>
<p>Put About Us content here</p>
<h1>About Us</h1>
<p>Put About Us content here</p>
Run the Application
Select Debug, Start Debugging (or F5) from the Visual Web Developer menu.Your application will look like this:
Click on the "Home" tab and the "About" tab to see how it works.
ASP.NET MVC - SQL Database
To learn ASP.NET MVC, we are Building an Internet Application.Part VI: Adding a Database.
Creating the Database
Visual Web Developer comes with a free SQL database called SQL Server Compact.The database needed for this tutorial can be created with these simple steps:
- Right-click the App_Data folder in the Solution Explorer window
- Select Add, New Item
- Select SQL Server Compact Local Database *
- Name the database Movies.sdf.
- Click the Add button
Visual Web Developer automatically creates the database in the App_Data folder.
Adding a Database Table
Double-clicking the Movies.sdf file in the App_Data folder will open a Database Explorer window.To create a new table in the database, right-click the Tables folder, and select Create Table.
Create the following columns:
Column |
Type |
Allow Nulls |
---|---|---|
ID |
int (primary key) |
No |
Title |
nvarchar(100) |
No |
Director |
nvarchar(100) |
No |
Date |
datetime |
No |
ID is an integer (whole number) used to identify each record in the table.
Title is a 100 character text column to store the name of the movie.
Director is a 100 character text column to store the director's name.
Date is a datetime column to store the release date of the movie.
After creating the columns described above, you must make the ID column the table's primary key (record identifier). To do this, click on the column name (ID) and select Primary Key. Also, in the Column Properties window, set the Identity property to True:
When you have finished creating the table columns, save the table and name it MovieDBs.
Note:
We have deliberately named the table "MovieDBs" (ending with s). In the next chapter, you will see the name "MovieDB" used for the data model. It looks strange, but this is the naming convention you have to use to make the controller connect to the database table.
Adding Database Records
You can use Visual Web Developer to add some test records to the movie database.Double-click the Movies.sdf file in the App_Data folder.
Right-click the MovieDBs table in the Database Explorer window and select Show Table Data.
Add some records:
ID |
Title |
Director |
Date |
---|---|---|---|
1 |
Psycho |
Alfred Hitchcock |
01.01.1960 |
2 |
La Dolce Vita |
Federico Fellini |
01.01.1960 |
ASP.NET MVC - Models
To learn ASP.NET MVC, we are Building an Internet Application.Part VII: Adding a Data Model.
MVC Models
The MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic.With MVC, models both hold and manipulate application data.
The Models Folder
The Models Folder contains the classes that represent the application model.Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application security.
AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel.
Adding a Database Model
The database model needed for this tutorial can be created with these simple steps:- In the Solution Explorer, right-click the Models folder, and select Add and Class.
- Name the class MovieDB.cs, and click Add.
- Edit the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcDemo.Models
{
public class MovieDB
{
public int ID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
public DateTime Date { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<MovieDB> Movies { get; set; }
}
}
Note:
We have deliberately named the model class "MovieDB". In the previous chapter, you saw the name "MovieDBs" (ending with s) used for the database table. It looks strange, but this is the naming convention you have to use to make the model connect to the database table.
Adding a Database Controller
The database controller needed for this tutorial can be created with these simple steps:- Re-Build your project: Select Debug, and then Build MvcDemo from the menu.
- In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
- Set controller name to MoviesController
- Select template: Controller with read/write actions and views, using Entity Framework
- Select model class: MovieDB (MvcDemo.Models)
- Select data context class: MovieDBContext (MvcDemo.Models)
- Select views Razor (CSHTML)
- Click Add
- A MoviesController.cs file in the Controllers folder
- A Movies folder in the Views
folder
Adding Database Views
The following files are automatically created in the Movies folder:- Create.cshtml
- Delete.cshtml
- Details.cshtml
- Edit.cshtml
- Index.cshtml
Adding a Connection String
Add the following element to the <connectionStrings> element in your Web.config file:<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|\Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
ASP.NET MVC – Security
To learn ASP.NET MVC, we are Building an Internet Application.Part VIII: Adding Security.
MVC Application Security
The Models Folder contains the classes that represent the application model.Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application authentication.
AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel:
The Change Password Model
public class ChangePasswordModel{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
The Logon Model
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
The Register Model
public class RegisterModel{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
ASP.NET MVC - HTML Helpers
HTML
Helpers are used to modify HTML output
HTML Helpers
With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In most cases, an HTML helper is just a method that returns a string.
With MVC, you can create your own helpers, or use the built in HTML helpers.
Standard HTML Helpers
MVC includes standard helpers for the most common types of HTML elements, like HTML links and HTML form elements.HTML Links
The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.
Razor Syntax:
@Html.ActionLink("About this Website", "About")
ASP Syntax:
<%=Html.ActionLink("About this Website", "About")%>
The first parameter is the link text, and the second parameter is the name of the controller action.
The Html.ActionLink() helper above, outputs the following HTML:
<a href="/Home/About">About this Website</a>
The Html.ActionLink() helper has several properties:
Property |
Description |
---|---|
.linkText |
The link text (label) |
.actionName |
The target action |
.routeValues |
The values passed to the action |
.controllerName |
The target controller |
.htmlAttributes |
The set of attributes to the link |
.protocol |
The link protocol |
.hostname |
The host name for the link |
.fragment |
The anchor target for the link |
Note:
You can pass values to a controller action. For example, you can pass the id of a database record to a database edit action:
Razor Syntax C#:
@Html.ActionLink("Edit Record", "Edit", new {Id=3})
Razor Syntax VB:
@Html.ActionLink("Edit Record", "Edit", New With{.Id=3})
The Html.ActionLink() helper above, outputs the following HTML:
<a href="/Home/Edit/3">Edit Record</a>
HTML Form Elements
There following HTML helpers can be used to render (modify and output) HTML form elements:- BeginForm()
- EndForm()
- TextArea()
- TextBox()
- CheckBox()
- RadioButton()
- ListBox()
- DropDownList()
- Hidden()
- Password()
eg.
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>
ASP.NET MVC - Publishing the Website
Learn how to publish an MVC application without using Visual Web Developer.Publish Your Application Without Using Visual Web Developer
An ASP.NET MVC application can be published to a remote server by using the Publish commands in WebMatrix ,Visual Web Developer, or Visual Studio.This function copies all your application files, controllers, models, images, and all the required DLL files for MVC, Web Pages, Razor, Helpers, and SQL Server Compact (if a database is used).
Sometimes you don't want to use this option. Maybe your hosting provider only supports FTP? Maybe you already have a web site based on classic ASP? Maybe you want to copy the files yourself? Maybe you want to use Front Page, Expression Web, or some other publishing software?
Will you get a problem? Yes, you will. But you can solve it.
To perform a web copy, you have to know how to include the right files, what DDL files to copy, and where store them.
Follow these steps:
1. Use the Latest Version of ASP.NET
Before you continue, make sure your hosting computer runs the latest version of ASP.NET (4.0).2. Copy the Web Folders
Copy your website (all folders and content) from your development computer to an application folder on your remote hosting computer (server).If your App_Data folder contains test data, don't copy the App_Data folder (see SQL Data below).
3. Copy the DLL Files
On the remote server create a bin folder in the root of your application. (If you have installed Helpers, you already have a bin folder)Copy everything from your folders:
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies
to your application's bin folder on the remote server.
4. Copy the SQL Server Compact DLL Files
If your application has a SQL Server Compact database (an .sdf file in App_Data folder), you must copy the SQL Server Compact DLL files:Copy everything from your folder:
C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Private
to your application's bin folder on the remote server.
Create (or edit) the Web.config file for your application:
eg.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add invariant="System.Data.SqlServerCe.4.0"
name="Microsoft SQL Server Compact 4.0"
description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1,Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
5. Copy SQL Server Compact Data
Do you have .sdf files in your App_Data folder that contains test data?Do you want to publish the test data to the remote server?
Most likely not.
If you have to copy the SQL data files (.sdf files), you should delete everything in the database, and then copy the empty .sdf file from your development computer to the server.
THAT'S IT. GOOD LUCK !
ASP.NET Razor
ASP.NET Razor - Markup
Razor is not a programming language. It's a server side markup language.What is Razor?
Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.Server-based code can create dynamic web content on the fly, while a web page is written to the browser. When a web page is called, the server executes the server-based code inside the page before it returns the page to the browser. By running on the server, the code can perform complex tasks, like accessing databases.
Razor is based on ASP.NET, and designed for creating web applications. It has the power of traditional ASP.NET markup, but it is easier to use, and easier to learn.
Razor Syntax
Razor uses a syntax very similar to PHP and Classic ASP.Razor:
eg.
<ul>
@for (int i = 0; i < 10; i++) {
<li>@i</li>
}
</ul>
PHP:
<ul>
<?php
for ($i = 0; $i < 10; $i++) {
echo("<li>$i</li>");
}
?>
</ul>
Web Forms (and Classic ASP):<?php
for ($i = 0; $i < 10; $i++) {
echo("<li>$i</li>");
}
?>
</ul>
<ul>
<% for (int i = 0; i < 10; i++) { %>
<li><% =i %></li>
<% } %>
</ul>
<% for (int i = 0; i < 10; i++) { %>
<li><% =i %></li>
<% } %>
</ul>
Razor Helpers
ASP.NET helpers are components that can be accessed by single lines of Razor code.You can build your own helpers using Razor syntax, or use built-in ASP.NET helpers.
Below is a short description of some useful Razor helpers:
- Web Grid
- Web Graphics
- Google Analytics
- Facebook Integration
- Twitter Integration
- Sending Email
- Validation
Razor Programming Languages
Razor supports both C# (C sharp) and VB (Visual Basic)ASP.NET Razor - C# and VB Code Syntax
Razor supports both C# (C sharp) and VB (Visual Basic).Main Razor Syntax Rules for C#
- Razor code blocks are enclosed in @{ ... }
- Inline expressions (variables and functions) start with @
- Code statements end with semicolon
- Variables are declared with the var keyword
- Strings are enclosed with quotation marks
- C# code is case sensitive
- C# files have the extension .cshtml
<!-- Single statement block -->
@{ var myMessage = "Hello World"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
Main Razor Syntax Rules for VB
- Razor code blocks are enclosed in @Code ... End Code
- Inline expressions (variables and functions) start with @
- Variables are declared with the Dim keyword
- Strings are enclosed with quotation marks
- VB code is not case sensitive
- VB files have the extension .vbhtml
eg.
<!-- Single statement block -->
@Code dim myMessage = "Hello World" End Code
<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@Code
dim greeting = "Welcome to our site!"
dim weekDay = DateTime.Now.DayOfWeek
dim greetingMessage = greeting & " Here in Huston it is: " & weekDay
End Code
<p>The greeting is: @greetingMessage</p>
How Does it Work?
Razor is a simple programming syntax for embedding server code in web pages.Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.
The Razor syntax gives you all the power of ASP.NET, but is using a simplified syntax that's easier to learn if you're a beginner, and makes you more productive if you're an expert.
Razor web pages can be described as HTML pages with two kinds of content: HTML content and Razor code.
When the server reads the page, it runs the Razor code first, before it sends the HTML page to the browser. The code that is executed on the server can perform tasks that cannot be done in the browser, for example accessing a server database. Server code can create dynamic HTML content on the fly, before it is sent to the browser. Seen from the browser, the HTML generated by server code is no different than static HTML content.
ASP.NET web pages with Razor syntax have the special file extension cshtml (Razor using C#) or vbhtml (Razor using VB).
Working With Objects
Server coding often involves objects.The "Date" object is a typical built-in ASP.NET object, but objects can also be self-defined, a web page, a text box, a file, a database record, etc.
Objects may have methods they can perform. A database record might have a "Save" method, an image object might have a "Rotate" method, an email object might have a "Send" method, and so on.
Objects also have properties that describe their characteristics. A database record might have a FirstName and a LastName property (amongst others).
The ASP.NET Date object has a Now property (written as Date.Now), and the Now property has a Day property (written as Date.Now.Day). The example below shows how to access some properties of the Date object:
eg.
<table border="1">
<tr>
<th width="100px">Name</th>
<td width="100px">Value</td>
</tr>
<tr>
<td>Day</td><td>@DateTime.Now.Day</td>
</tr>
<tr>
<td>Hour</td><td>@DateTime.Now.Hour</td>
</tr>
<tr>
<td>Minute</td><td>@DateTime.Now.Minute</td>
</tr>
<tr>
<td>Second</td><td>@DateTime.Now.Second</td>
</tr>
</td>
</table>
If and Else Conditions
An important feature of dynamic web pages is that you can determine what to do based on conditions.The common way to do this is with the if ... else statements:
eg.
@{
var txt = "";
if(DateTime.Now.Hour > 12)
{txt = "Good Evening";}
else
{txt = "Good Morning";}
}
<html>
<body>
<p>The message is @txt</p>
</body>
</html>
Reading User Input
Another important feature of dynamic web pages is that you can read user input.Input is read by the Request[] function, and posting (input) is tested by the IsPost condition:
eg.
@{
var totalMessage = "";
if(IsPost)
{
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
<html>
<body style="background-color: beige; font-family: Verdana, Arial;">
<form action="" method="post">
<p><label for="text1">First Number:</label><br>
<input type="text" name="text1" /></p>
<p><label for="text2">Second Number:</label><br>
<input type="text" name="text2" /></p>
<p><input type="submit" value=" Add " /></p>
</form>
<p>@totalMessage</p>
</body>
</html>
ASP.NET Razor - C# Variables
Variables are named entities used to store data.Variables
Variables are used to store data.The name of a variable must begin with an alphabetic character and cannot contain whitespace or reserved characters.
A variable can be of a specific type, indicating the kind of data it stores. String variables store string values ("Welcome to W3Schools"), integer variables store number values (103), date variables store date values, etc.
Variables are declared using the var keyword, or by using the type (if you want to declare the type), but ASP.NET can usually determine data types automatically.
eg.
// Using the var keyword:
var greeting = "Welcome to W3Schools";
var counter = 103;
var today = DateTime.Today;
// Using data types:
string greeting = "Welcome to W3Schools";
int counter = 103;
DateTime today = DateTime.Today;
Data Types
Below is a list of common data types:
Type |
Description |
Examples |
---|---|---|
int |
Integer (whole numbers) |
103, 12, 5168 |
float |
Floating-point number |
3.14, 3.4e38 |
decimal |
Decimal number (higher precision) |
1037.196543 |
bool |
Boolean |
true, false |
string |
String |
"Hello W3Schools", "John" |
Operators
An operator tells ASP.NET what kind of command to perform in an expression.The C# language supports many operators. Below is a list of common operators:
Operator |
Description |
Example |
---|---|---|
= |
Assigns a value to a variable. |
i=6 |
+ - * / |
Adds a value or variable. Subtracts a value or variable. Multiplies a value or variable. Divides a value or variable. |
i=5+5 i=5-5 i=5*5 i=5/5 |
+= -= |
Increments a variable. Decrements a variable. |
i += 1 i -= 1 |
== |
Equality. Returns true if values are equal. |
if (i==10) |
!= |
Inequality. Returns true if values are not equal. |
if (i!=10)
|
< > <= >= |
Less than. Greater than. Less than or equal. Greater than or equal. |
if (i<10) if (i>10) if (i<=10) if (i>=10) |
+ |
Adding strings (concatenation). |
"w3" + "schools" |
. |
Dot. Separate objects and methods. |
DateTime.Hour |
() |
Parenthesis. Groups values. |
(i+5) |
() |
Parenthesis. Passes parameters. |
x=Add(i,5) |
[] |
Brackets. Accesses values in arrays or collections. |
name[3] |
! |
Not. Reverses true or false. |
if (!ready) |
&& || |
Logical AND. Logical OR. |
if (ready && clear) if (ready || clear) |
Converting Data Types
Converting from one data type to another is sometimes useful.The most common example is to convert string input to another type, such as an integer or a date.
As a rule, user input comes as strings, even if the user entered a number. Therefore, numeric input values must be converted to numbers before they can be used in calculations.
Below is a list of common conversion methods:
Method |
Description |
Example |
---|---|---|
AsInt() IsInt() |
Converts a string to an integer. |
if (myString.IsInt()) {myInt=myString.AsInt();} |
AsFloat() IsFloat() |
Converts a string to a floating-point number. |
if (myString.IsFloat()) {myFloat=myString.AsFloat();} |
AsDecimal() IsDecimal() |
Converts a string to a decimal number. |
if (myString.IsDecimal()) {myDec=myString.AsDecimal();} |
AsDateTime() IsDateTime() |
Converts a string to an ASP.NET DateTime type. |
myString="10/10/2012"; myDate=myString.AsDateTime(); |
AsBool() IsBool() |
Converts a string to a Boolean. |
myString="True"; myBool=myString.AsBool(); |
ToString() |
Converts any data type to a string. |
myInt=1234; myString=myInt.ToString(); |
ASP.NET Razor - C# Loops and Arrays
Statements can be executed repeatedly in loops.For Loops
If you need to run the same statements repeatedly, you can program a loop.If you know how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:
eg.
<html>
<body>
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
</body>
</html>
For Each Loops
If you work with a collection or an array, you often use a for each loop.A collection is a group of similar objects, and the for each loop lets you carry out a task on each item. The for each loop walks through a collection until it is finished.
The example below walks through the ASP.NET Request.ServerVariables collection.
eg.
<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>
While Loops
The while loop is a general purpose loop.A while loop begins with the while keyword, followed by parentheses, where you specify how long the loop continues, then a block to repeat.
While loops typically add to, or subtract from, a variable used for counting.
In the example below, the += operator adds 1 to the variable i, each time the loop runs.
eg.
<html>
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line @i</p>
}
}
</body>
</html>
Arrays
An array is useful when you want to store similar variables but don't want to create a separate variable for each of them:eg.
@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai")+1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
ASP.NET Razor - C# Logic Conditions
Programming Logic: Execute code based on conditions.The If Condition
C# lets you execute code based on conditions.To test a condition you use an if statement. The if statement returns true or false, based on your test:
- The if statement starts a code block
- The condition is written inside parenthesis
- The code inside the braces is executed if the test is true
@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
The Else Condition
An if statement can include an else condition.The else condition defines the code to be executed if the condition is false.
eg.
@{var price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
Note: In the example above, if the first condition is true, it will be executed. The else condition covers "everything else".
The Else If Condition
Multiple conditions can be tested with an else if condition:eg.
@{var price=25;}
<html>
<body>
@if (price>=30)
{
<p>The price is high.</p>
}
else if (price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
In the example above, if the first condition is true, it will be executed.
If not, then if the next condition is true, this condition will be executed.
You can have any number of else if conditions.
If none of the if and else if conditions are true, the last else block (without a condition) covers "everything else".
Switch Conditions
A switch block can be used to test a number of individual conditions:eg.
@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@switch(day)
{
case "Monday":
message="This is the first weekday.";
break;
case "Thursday":
message="Only one day before weekend.";
break;
case "Friday":
message="Tomorrow is weekend!";
break;
default:
message="Today is " + day;
break;
}
<p>@message</p>
</body>
</html>
The test value (day) is in parentheses. Each individual test condition has a case value that ends with a colon, and any number of code lines ending with a break statement. If the test value matches the case value, the code lines are executed.
A switch block can have a default case (default:) for "everything else" that runs if none of the cases are true.
0 comments:
Post a Comment