In this article I will explain a tutorial with example, how to create and implement a simple Blog in ASP.Net using C# and VB.Net.
The Blog will be implemented using database and each Blog will have a unique URL implemented with the help URL Routing feature.
 
 
Database
Below is the schema of the Table that will be used for saving Blogs.
Simple Blog Tutorial with example in ASP.Net using C# and VB.Net
 
Note: The SQL for creating the database is provided in the attached sample code.
 
 
Namespaces
The following namespaces will be used on all the pages used for this article.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Adding Blogs
In order to add Blog, a page named AddBlog.aspx is used.
HTML Markup
The following HTML Markup consists of an HTML form to allow user insert the details of the Blog such as its Title and Body to database. The Body TextBox is a Multiline TextBox and is made a Rich TextBox using the TinyMCE RichTextEditor plugin.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Title:
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txtTitle" runat="server" Width = "550" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Body:
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
        </td>
    </tr>
</table>
<script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
    tinymce.init({ selector: 'textarea' });
</script>
 
Code
The following event handler is used to save the details of the Blog to the database table.
C#
protected void Submit(object sender, EventArgs e)
{
    string query = "INSERT INTO [Blogs] VALUES (@Title, @Body)";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@Title", txtTitle.Text);
            cmd.Parameters.AddWithValue("@Body", txtBody.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("~/Default.aspx");
        }
    }
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim query As String = "INSERT INTO [Blogs] VALUES (@Title, @Body)"
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand(query, con)
            cmd.Parameters.AddWithValue("@Title", txtTitle.Text)
            cmd.Parameters.AddWithValue("@Body", txtBody.Text)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Response.Redirect("~/Default.aspx")
        End Using
    End Using
End Sub
 
 
URL Routing Implementation
Once the Blogs are inserted, the next task is to implement URL Routing so that we can access the Blogs through the browser.
Hence you will need to add a Global.asax file and in that you need to register the Route which sends the requests to a page named DisplayBlog.aspx page (explained later).
C#
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>
<script RunAt="server">
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
 
    static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("DisplayBlog", "Blogs/{BlogId}/{Slug}.aspx", "~/DisplayBlog.aspx");
    }
</script>
 
VB.Net
<%@ Application Language="VB" %>
<%@ Import Namespace="System.Web.Routing" %>
<script RunAt="server">
    Private Sub Application_Start(sender As Object, e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
 
    Private Shared Sub RegisterRoutes(routes As RouteCollection)
        routes.MapPageRoute("DisplayBlog", "Blogs/{BlogId}/{Slug}.aspx", "~/DisplayBlog.aspx")
    End Sub
</script>
 
Note: URL Routing is available only in .Net 3.5 SP1 and higher frameworks. If you are unable to understand this concept, please refer my article Implement URL routing in ASP.Net Web Forms.
 
 
Displaying Blog from database
For displaying the Blog from database, a page named DisplayBlog.aspx is used.
HTML Markup
The HTML Markup consists of Labels to display the Title and Body of the Blog.
<h2>
    <asp:Label ID="lblTitle" runat="server" /></h2>
<hr />
<asp:Label ID="lblBody" runat="server" />
 
Code
Inside the Page Load event handler, the ID of the Blog is fetched from the RouteData values.
Then using the BlogId, the other details such as Title and Body are fetched from the database and displayed using Label controls.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.PopulateBlog();
    }
}
 
private void PopulateBlog()
{
    string blogId = this.Page.RouteData.Values["BlogId"].ToString();
    string query = "SELECT [Title], [Body] FROM [Blogs] WHERE [BlogId] = @BlogId";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Parameters.AddWithValue("@BlogId", blogId);
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    lblTitle.Text = dt.Rows[0]["Title"].ToString();
                    lblBody.Text = dt.Rows[0]["Body"].ToString();
                }
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.PopulateBlog()
    End If
End Sub
 
Private Sub PopulateBlog()
    Dim blogId As String = Me.Page.RouteData.Values("BlogId").ToString()
    Dim query As String = "SELECT [Title], [Body] FROM [Blogs] WHERE [BlogId] = @BlogId"
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.Parameters.AddWithValue("@BlogId", blogId)
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    lblTitle.Text = dt.Rows(0)("Title").ToString()
                    lblBody.Text = dt.Rows(0)("Body").ToString()
                End Using
            End Using
        End Using
    End Using
End Sub
 
 
Displaying the List of Blogs
Once the Blog details are inserted in database, the AddBlog.aspx page redirects the user to Default.aspx page where user can view the list of all the Blogs inserted in the database.
 
HTML Markup
The HTML Markup consists of a HyperLink to allow user access the AddBlog.aspx page and a Repeater control to display the list of the Blogs present in the database.
You will notice that the NavigateUrl of the HyperLink has a URL similar to that of the Route registered earlier in the Global.asax file.
<h2>
    Blogs</h2>
<br />
<asp:HyperLink ID="HyperLink1" NavigateUrl="~/AddBlog.aspx" Text="Add Blog" runat="server" />
<hr />
<asp:Repeater ID="rptPages" runat="server">
    <ItemTemplate>
        <%# Container.ItemIndex + 1 %>
        <asp:HyperLink ID="HyperLink2" NavigateUrl='<%# string.Format("~/Blogs/{0}/{1}.aspx", Eval("BlogId"), Eval("Slug")) %>'
            Text='<%# Eval("Title") %>' runat="server" />
    </ItemTemplate>
    <SeparatorTemplate>
        <br />
    </SeparatorTemplate>
</asp:Repeater>
 
Code
The Repeater control is populated with the list of Blogs saved in the database table in the Page Load event.
Here Slug i.e. the Title present in the URL is created by replacing space character with hyphen character.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.PopulateBlogs();
    }
}
 
private void PopulateBlogs()
{
    string query = "SELECT [BlogId], [Title], REPLACE([Title], ' ', '-') [SLUG], [Body] FROM [Blogs]";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    rptPages.DataSource = dt;
                    rptPages.DataBind();
                }
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.PopulateBlogs()
    End If
End Sub
 
Private Sub PopulateBlogs()
    Dim query As String = "SELECT [BlogId], [Title], REPLACE([Title], ' ', '-') [SLUG], [Body] FROM [Blogs]"
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    rptPages.DataSource = dt
                    rptPages.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
 
 
Screenshot
Simple Blog Tutorial with example in ASP.Net using C# and VB.Net
 
 
Errors
The following errors you might encounter while implementing the Blog.
Simple Blog Tutorial with example in ASP.Net using C# and VB.Net
The above error will occur when you have not implemented the Routing properly and trying to access the blogs.
 
Simple Blog Tutorial with example in ASP.Net using C# and VB.Net
The above error occurs when ASP.Net detects HTML content posted to the server and hence to solve this error please refer my article ASP.Net Error: A potentially dangerous Request.Form value was detected from the client.
 
 
Downloads