XML is a cross-platform, hardware and software independent, text based markup language, which enables you to store data in a structured format by using meaningful tags. XML stores structured data in XML documents that are similar to databases. Notice that unlike Databases, XML documents store data in the form of plain text, which can be used across platforms.

In an XML document, you specify the structure of the data by creating a DTD or an XML schema. When you include a DTD in an XML document, the software checks the structure of the XML document against the DTD. This process of checking the structure of the XML document is called validating. The software performing the task of validating is called a validating parser.
The following code defines the structure of an XML document that will store data related to books:
<?xml version="1.0"?>
<Books>
  <Book bid="B001">
    <Title> Understanding XML </Title>
    <Price> $30 </Price> 
    <author>
      <FirstName> Lily </FirstName>
      <LastName>
        Hicks <LastName>
        </author>
  </Book>
  <Book bid="B002">
    <Title> .NET Framework </Title>
    <Price> $45 </Price> 
    <author>
      <FirstName> Jasmine </FirstName>
      <LastName>
        Williams <LastName>
        </author>
  </Book>
</Books>

.NET Support for XML

The .NET Framework has extensive support for working with XML documents. IN the .NET framework, the support for XML documents includes:
  • XML namespace
  • XML designer
  • XML Web Server control
  • XML DOM support

XML Namespace

The System.Xml namespace provides a rich set of classes for processing XML data. The commonly used classes for working with XML data are:
  • XmlTextReader: Provides forward only access to a stream of XML data and checks whether or not an XML document is well formed. This class neither creates as in-memory structure nor validates the XML document against the DTD. You can declare an object of the XmlTextReader class by including the System.Xml namespace in the application. The syntax to declare an object of this class is as follows:
    XmlTextReader reader = new XmlTextReader("XML1.xml");
It is important to note that the .xml file you pass as an argument to the constructor of the  XmlTextReader class exists in the \WINNT\System32  folder.
  • XmlTextWriter: Provides forward only way of generating streams or files containing XML data that conforms to W3C XML 1.0. If you want to declare an object of the XmlTextWriter class, you must include the System.Xml. The syntax to decare an object of this class is as follows:
    XmlTextWriter writer = new XmlTextWriter(Response.Output);
Here Response.Output represents an outgoing HTTP response stream to which you want to send the XML data.
  • XmlDocument: Provides navigating and edinting features of the nodes in an XML document tree. XmlDocument is the most frequently used class in ASP.NET applications that use XML documents. It also supports W3C XML DOM. XML DOM is an in-memory representation of an XML document. It represents data in the form of hierarchically organized object nodes and allows you to programmatically access and manipulate the elements and attributes present in an XML document.
    XmlDocument doc = new XmlDocument();
  • XmlDataDocument: Provides support for XML and relational data in W3C XML DOM. You can use this class with a dataset to provide relational and non-relational views of the same set of data. This class is primarily used when you want to access the functions of ADO.NET. The syntax to declare an object of this class is as follows:
DataSet ds=new DataSet();
XmlDataDocument doc=new XmlDocument(ds);
    There are a number of reasons to use XmlDataDocument:
  • It gives you the freedom to work with any data by using the DOM.
  • There is synchronization between an XmlDatadocument and a DataSet, and any changes in one will be  reflected in the other.
  • When an XML document is loaded into an XmlDatadocument, the schema is preserved.
      You need to include System.Xml namespace.
  • XmlPathDocument: Provides a read-only cache for XML document processing by using XSLT. This class is optimizied for XSLT processing and does not check for the conformity of W3C DOM. For this reason, you can create an instance of this class to process an XML document faster. To create an instance of the XPathDocument class, you need to include the System.Xml.XPath namespace in the application. The Syntax to declare an object of this class is as follows:
XmlPathDocument doc=new XmlPathDocument("XML1.xml");
  • XmlNodeReader: Provides forward-only access to the data represented by the XmlDocument or XmlDataDocument class. If you want to create an instance of the XmlNodeReader class, you need to include the System.Xml namespace. The syntax to declare an object of this class is as follows:
XmlDocument doc=new XmlPathDocument();
XmlNodeReader reader=new XmlNodeReader(doc);
  • XslTransform: Provides support for a XSLT 1.0 style sheet syntax that enables you to transform an XML document by using XSL style sheets. If you want to create an instance of the XslTransform class, you need to include the System.Xml.Xsl namespace in the application. The syntax to declare an object of this class is as follows:
Xsltransform xslt = new XslTransform ();

XML Designer

Visual Studio .NET provides the XML designer that you can use to create and edit XML documents. For example, if you need to create an XML document that contains the details of books available in an online bookstore, you need to perform the following steps by using the XML designer of Visual Studio .NET:

  1. Create a new ASP.NET Web application.
  2. Select the Add New Item option
  3. Select XML File as the template from the right pane.  Specify the name as "books.xml" and click open.
  4. The XML designer is displayed. The XML designer has automatically generated a line that notifies the browser that the document being processed is an XML document, as displayed in the figure:
  5.   At the bottom of the designer window, there are two tabs, XML and Data. In the XML tab enter the following lines of code after the first line in  the XML designer:
The Data view displays the XML data represented by the XML document. When you switch to the Data view, the data appears, as displayed in the following figure:
In addition to just viewing data in the Data view, you can also add data directly to an existing XML document. For this, just click on the new row below the existing data and enter your values, and shown in the figure:

XML Web Server Control

An XML Web Server control is used to display the contents of an XML document without formatting or using XSL Transformations. You can optionally specify a XSLT style sheet that formats the XML document before it is displayed in an XML server control. The XML Web Server control belongs to the System.Web.UI.WebControls namespace. You can add an XML Web Server control to a Web form by dragging the control from the Web forms tab of the toolbox.
The XML Web Server control has the following properties:
  • DocumentSource: Allows you to specify the URL or the path of the XML document to be displayed in the Web form.
  • TransformSource: Allows you to specify the URL of the XSLT file, which transforms the XML document into the required format before it is displayed in the Web form.
  • Document: Allows you to specify a reference to an object of the XMLDocument class. This property is available only at runtime.
  • Transform: Allows you to specify a reference to an object of the XMLTransform class. This property is available only at runtime.
A practical example for the same is shown in the last section of this tutorial.

XML Document Object Model Support

When you want to access and display XML data in Web Applications, you use the XML Web server control and set its properties at design time. In certain situation, you may need to display the XML data based on specific conditions. In such cases, you will have to access the XML data programmatically.
An XML document consists of elements and attributes. For this reason, you can access XML data programmatically. Note that XML DOM allows you to access and manipulate the elements and attributes present in an XML document programmatically.
To implement XML DOM, the .NET framework provides a set of additional classes included in the System.Xml namespace. These classes enable you to access the XML data programmatically. Some of the classes in the System.Xml namespace are as follows:
  • XmlDocumentType: Represents the DTD used by an XML document.
  • XmlElement: Represents one element from an XML document.
  • XmlAttribute: Represents one attribute of an element.

Bind XML Data to Web Form Controls

An XML document cannot be directly bound to server controls. To implement data binding, you first need to load the XML document into a DataSet. Then, you can bind server control with this DataSet.
The Dataset object has a ReadXml method, which is used to read data into the DataSet from an XML file. The ReadXml method can read XML documents from the Stream, File, TextReader, and XmlReader sources. The synatx for the ReadXml method is as follows:
ReadXml (Stream | FileName | textReader | XmlReader , XmlReadMode )
The XmlReadMode parameter can take any of the values listed in the following table:
VALUES
DESCIPTION
 Auto Checks the XML document and selects the action accordingly from the following choices:
1. If the DataSet already has schema or the  document contains an inline  schema, it sets XmlReadMode to ReadSchema.
 2. If the DataSet does not already have a schema and the document does not contain an inline schema, it sets XmlReadMode to InferSchema.
DiffGram Reads a Diffgram, which is a format that contains both the original and the current values of the data, and applies changes from the DiffGram to the DataSet.
 Fragment The default namespace is read as the inline schema.
 IgnoreSchema Ignores any inline schema and reads data into the existing DataSet schema.
InferSchema Ignores any inline schema and instead infers schema from the data and loads the data.
ReadSchema Reads any inline schema and loads the data. If the DataSet already has a schema, new tables may be added to the schema but an exception is thrown if any tables in the inline schema already exist in the DataSet.
Consider that you want to represent "books.xml", with a DataSet. For this you can read the "books.xml" file into a DataSet and bind the XML document control to the DataGrid control by adding the following code to the Load event of the page in the .aspx page.
private void Page_Load(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml (MapPath("books.xml"));
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}

Working With XML Server Controls - Practical Example

The WebShoppe Web Site needs to create a Web application to store the details of the books available for sale in the XML format. The details of the books should be displayed in a tabular format in a browser. The details include Book Id, Title, price, First Name and Last Name of the author.
Solution: It is pertinent to note that XSLT is the W3C specification for formatting XML documents and displaying the contents in the required format. You need to create an .xsl file by using Visual Studio .NET IDE to display the data stored in the XML document in a tabular format. An XML Web server control is used to display the contents of an XML document in Web application. You need to add an XML Web Server control from the toolbox  to the Web form to display the relevant XML data in the Web application.
1. Open your Web application, and add an item XML file, in the same manner as shown before. So, now considering that you have added "books.xml" using the XML designer to your web application, let us move to next step.
2. Select Add New Item option from the project menu to open the Add New Item dialog box.
3. Select XSLT File as the template form the right pane.
4. Add a few lines of code after the second line (since two lines are automatically generated). To see this code you can download the project through the link at the end of this section.
Now that you have created the XML file with the relevant data, and also specified the style sheet for the XML file.
5. Next, you need to apply the style sheet to the XML data by adding an XML server control to the WebForm1.aspx and setting the DocumentSource and TransformSource properties to .xml file and .xsl file respectively.
Build your application and run it. The output should be as follows:
You can download this application through this link.

Converting Relational Data into an XML document

ASP.NET allows you to easily convert the data form a database into an Xml document. It provides the XMLDataDocument class, which allows you to load relational data and the data from an XML document into a DataSet. The data loaded in XMLDataDocument can be manipulated using the W3C DOM.
Let us consider a problem: you need to extract data from a SQL Server and store it as an XML file.
Solution: For this we'll add an XML Web server control and a label to display ant error message. The code for the same is written below:
using System.Data.SqlClient;
using System.Xml;
Now add this code:
//Create a dataset
Dataset ds = new Dataset();
//Create a connection string.
String sqlconnect = "Persist Security Info=False;User ID=sa;Initial Catalog=WebShoppe;Data Source=IRDTEST-D190;";
//Create a connection object to connect to the web shoppe database
try
{
SqlConnection nwconnect = new SqlConnection(sqlconnect);
//Create a command string to select all the customers in the customerDetails table
String scommand = "Select * form customerDetails";
//Create an adapter to load the dataset
SqlDataAdapter da = new SqlDataAdapter(scommand,nwconnect);
//Fill the dataset
da.Fill(ds,"customerDetails");
}
catch
{
Label1.Text = "Error while connecting to database";
}
XmlDataDocument doc = new XmlDataDocument(ds);
Xml1.Document = doc;
doc.Save(MapPath("Customers.xml"));//This is where we are saving the data in an XML file Customers.xml
The above code will display the contents not in a tabular format, since no style sheets are attached. If you want the data to be displayed in some particular format, make your XSL file as myfile.xsl and add the following three lines of code to the above written code:
XslTransform t = new XslTransform();
t.Load(MapPath(("myfile.xsl"));
Xml1.Transform = t;

 

Introduction
Stored procedures (sprocs) are generally an ordered series of Transact-SQL statements bundled into a single logical unit. They allow for variables and parameters, as well as selection and looping constructs. A key point is that sprocs are stored in the database rather than in a separate file.

Advantages over simply sending individual statements to the server include:
  1. Referred to using short names rather than a long string of text; therefore, less network traffiic is required to run the code within the sproc.
  2. Pre-optimized and precompiled, so they save an incremental amount of time with each sproc call/execution.
  3. Encapsulate a process for added security or to simply hide the complexity of the database.
  4. Can be called from other sprocs, making them reusable and reducing code size.
Parameterization

A stored procedure gives us some procedural capability, and also gives us a performance boost by using mainly two types of parameters:

  • Input parameters
  • Output parameters
From outside the sproc, parameters can be passed in either by position or reference.

Declaring Parameters

  1. The name
  2. The datatype
  3. The default value
  4. The direction
The syntax is :                     

@parameter_name [AS] datatype [= default|NULL] [VARYING] [OUTPUT|OUT]

Let's now create a stored procedure named "Submitrecord".

First open Microsoft SQL Server -> Enterprise Manager, then navigate to the database in which you want to create the stored procedure and select New Stored Procedure.

@1.gif

See the below Stored Procedure Properties for what to enter, then click OK.

2.gif

Now create an application named Store Procedure in .net to use the above sprocs.

Stored Procedure.aspx page code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server"><title>Store Procedure</title>
</
head>
<
body><form id="form1" runat="server"><div><asp:Label ID="Label1" runat="server" Text="ID"></asp:Label><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br /><asp:Label ID="Label2" runat="server" Text="Password"></asp:Label><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br /><asp:Label ID="Label3" runat="server" Text="Confirm Password"></asp:Label><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br /><br /><asp:Label ID="Label4" runat="server" Text="Email ID"></asp:Label><asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br /><br /><br /><asp:Button ID="Button1" runat="server" Text="Submit Record" OnClick="Button1_Click" /></div></form>
</
body>
</
html>

Stored Procedure.aspx.cs page code
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.SqlClient;public partial class _Default : System.Web.UI.Page
{
    
DataSet ds = new DataSet();
    
SqlConnection con;
     //Here we declare the parameter which we have to use in our application
    
SqlCommand cmd = new SqlCommand();
    
SqlParameter sp1 = new SqlParameter();
    
SqlParameter sp2 = new SqlParameter();
    
SqlParameter sp3 = new SqlParameter();
    
SqlParameter sp4 = new SqlParameter();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)

{
     con =
new SqlConnection("server=(local); database= gaurav;uid=sa;pwd=");
     cmd.Parameters.Add(
"@ID", SqlDbType.VarChar).Value = TextBox1.Text;
     cmd.Parameters.Add(
"@Password", SqlDbType.VarChar).Value = TextBox2.Text;
     cmd.Parameters.Add(
"@ConfirmPassword", SqlDbType.VarChar).Value = TextBox3.Text;
     cmd.Parameters.Add(
"@EmailID", SqlDbType.VarChar).Value = TextBox4.Text;
     cmd =
new SqlCommand("submitrecord", con);
     cmd.CommandType =
CommandType.StoredProcedure;
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
}
}

When we run the application, the window will look like this:

3.gif

After clicking the submit button the data is appended to the database as seen below in the SQL Server table record:

4.gif
How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX
 
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.
Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.
Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:
<form id="form1" runat="server">    
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>
        <div>
        <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />
        <br />
        <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>
        &nbsp;
        <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox>&nbsp;<br />
            </div>
    </form>
Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.
<connectionStrings>
            <removename="all"/>
            <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
      </connectionStrings>
Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.
C#
public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            conn = new SqlConnection(connection);
            string sql = "Select ContactName from Customers where CustomerId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            return contNm;
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }
VB.NET
 Public Shared Function GetContactName(ByVal custid As String) As String
        If custid Is Nothing OrElse custid.Length = 0 Then
            Return String.Empty
        End If
        Dim conn As SqlConnection = Nothing
        Try
            Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
            conn = New SqlConnection(connection)
            Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
            Dim cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("CustID", custid)
            conn.Open()
            Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
            Return contNm
        Catch ex As SqlException
            Return "error"
        Finally
            conn.Close()
        End Try
    End Function
Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
VB.NET
<System.Web.Services.WebMethod()> _
    Public Shared Function GetContactName(ByVal custid As String) As String
   End Function
At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.
function CallMe(src,dest)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
 }
 
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
 
Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server">    
………
Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
C#
if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
            txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
        }
VB.NET
If (Not Page.IsPostBack) Then
                  txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
                  txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If
As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.
Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.
Troubleshooting: ‘PageMethods Is 'Undefined'’ error
 
1.    Try setting EnablePageMethods="true" in the script manager tag
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
2.    Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.
 
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server"> 
    </form>
</body>
 
3.    Page methods needs to be static in code behind.

This article is about ASP.Net web pages that are a combination of HTML, C# and Razor syntax which produces dynamic web pages. They are not ASP.Net Web Forms because we can't use any ASP.Net server-side control and it is not the same as ASP.Net MVC because it does not follow the MVC design pattern; it uses an inline page model.

For this sample application, I have used Visual Studio 2012 RC, ASP.Net Web Page2 Betac and .Net Fx 4.5 RC.

First we will try with simple hello world application.

Step 1: Create a new web site in VS 2012 RC.

ASPWbPg1.jpg

Step 2: Select Visual C# and select ASP.Net Web Razor V2. Give the web site name the "HelloWorld" as depicted in the following image:

ASPWbPg2.jpg

Step 3: Once you have created the web site, you might add many existing pages, folders and assembly references. I will explain that in a different article.

Right-click on the project name in Solution Explorer-> Add New Item.

You will see the following Add new Item window and select new Content Page and give it the name "HelloWorld.cshtml". Refer to the following image:

ASPWbPg3.jpg

Step 4:

Double-click or open the newly added "helloworld.cshtml" page:

Here you will see, two sets of code blocks:


  1. Server side code block and
  2. HTML code block.
1. Server side code block

The server-side code block starts with "@{" and ends with the "}" symbol.

Ex :
@{    Page.Title = "Title goes here";
         
//Layout = "Your Layout Page goes here";}

Page.Title refers to the page title and you change this title using server-side coding/programming.

Layout refers to the URL for the layout page.

If you want to call a server-side variable or if it is a single-line statement, then start the one-line coding with the "@" symbol.
Ex :
@sayhello
2. HTML code block

The HTML code block is just a placeholder for the HTML.

Ex:
<div>  </div>
Now we will do some changes on the existing code.
Page.Title = "Hello World";
Layout =
"~/_SiteLayout.cshtml";var sayhello = "Hello World ! Welcome to Asp.net Web Pages 2.";
The above code creates a new variable called "sayhello" that can be used anywhere in the current page.

To display this variable value, we need a HTML control. In this case, I have created a span tag inside the div control which is in a HTML code block:
<div>    <span>    </span></div>
To call the sayhello variable, the following code should be used:@sayhello
Finally, the HTML code block looks like the following one:
<div>    <span>        @sayhello
   
</span></div>ASPWbPg4.jpg

Press F5 to run the application in your default browser.

Step 5:

You will see the page title as "Hello World - My ASP.NET Web Page". You might be wondering, from where "- My ASP.NET Web Page" is coming. This is coming from the Layout page. As of now, just ignore this text "- My ASP.NET Web Page".

In the body of the page you will see, "Hello World ! Welcome to Asp.net Web Pages 2." This value comes from the server-side variable @sayhello to HTML code block.

The Header and Footer sections are coming from the layout page.

ASPWbPg5.jpg

Step 6:

If you look at the page source, it is a clean HTML and there is no view state information and server-side code information:

ASPWbPg6.jpg