ASP.NET 4.5 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASPHostPortal.com Announces Cheap Magento 1.9.1.1 Hosting Solution

clock May 26, 2015 07:47 by author Dan

ASPHostPortal.com serve people since 2008 and we know how to deliver Powerful, Fast and Reliable Magento Hosting with the Superior Customer Support. Our superior servers are housed in US, UK, France, Germany, Netherlands, Australia, and Singapore with up to 100MB/s connection and Cisco Hardware Firewalls. Fully managed and monitored around the clock, our servers run on Windows Operating system with lots of memory (RAM) and up multiple Quad-Core Xeon CPU's, utilizing power of the Cloud Services. Our Magento Hosting plans come with up to 99.99% uptime and 30-Day Full Money Back Guarantee. Today, we offer high quality Magento 1.9.1.1 hosting at cheap price.

Magento hosting is currently available from hundreds of thousands of providers. The decision of what Magento hosting company to use can be the difference between the success and the demise of a Magento shopping cart website. While any Magento hosting, eCommerce hosting, or even generic web hosting company may look the same at first glance- placed in very simple terms, nothing could be further from the truth.

Security is a topic that's crucial for any eCommerce web site. If your site stores valuable financial info such as credit card numbers and personal contacts, as most Magento shops do, the severity of this topic is multiplied. No organization can afford to risk the devastating effects of having such data compromised. Many Magento hosting environments consist of private, virtual partitions of a server. This protects against a number of potential exploits that can be opened up by irresponsible webmasters that might otherwise share a server with your Magento shopping cart site.

ASPHostPortal.com provides Premium Magento 1.9.1.1 hosting plans on high performance servers and high-speed internet connection in the world. We provide high quality Magento hosting at an affordable price. We care for the clients, ensuring each and every client is more than just satisfied day in and day out. We only use the best hardware, super fast network, covered by 24/7 Support Team. To learn more about Magento 1.9.1.1 Hosting, please visit http://asphostportal.com/Magento-Hosting

About ASPHostPortal.com :
ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Fix ASP.NET Menu Control Cannot Work in Google Chrome

clock May 22, 2015 06:16 by author Dan

Problem

If your website is using ASP.NET Menu Control, the menu part will not work in Google Chrome browser and Apple Safari browser. The look and feel of the main menu is different. Submenu does not show up.

Solution

There is an easy fix for this problem. Just copy and paste the following codes to your page load event of your code behind master page file. You may need to copy it to every page if you do not use master page.

     Partial Class Main
        Inherits System.Web.UI.MasterPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Request.UserAgent.IndexOf("AppleWebKit") > 0 Then
                Request.Browser.Adapters.Clear()
            End If
        End Sub
    End Class

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASPHostPortal.com Announces Cheap Microsoft OWIN 3.0.1 Hosting Solution

clock May 18, 2015 11:46 by author Dan

ASPHostPortal.com is a web hosting provider dedicated to providing high quality web hosting at an affordable price. We care for the clients, ensuring each and every client is more than just satisfied day in and day out. We only use the best hardware, super fast network, covered by 24/7 Support Team. We have locations in 7 world class data centers, located USA, UK, France, Germany, Netherlands, Singapore and Australia. Each of locations will provide with amazing performance. Today, we offer high quality Microsoft OWIN 3.0.1 hosting at cheap price.

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools. Microsoft Owin 3.0.1 Provides a set of helper types and abstractions for simplifying the creation of OWIN components.

With IIS supporting Owin it is possible to run other Owin-enabled frameworks such as Nancy on IIS. With Microsoft’s web frameworks depending on Owin and not IIS it is possible to run those in other environments, such as self hosting within a process or on a web server on linux running Mono. SignalR and Web API already uses Owin which means that they can be self hosted and other cool stuff. ASP.NET MVC6 which is part of ASP.NET vNext will be completely based on Owin. Transfer your host to ASPHostPortal.com to get faster and cheaper Microsoft OWIN solution.

We have established thousands of connections worldwide and multiple points of presence both domestically in the United States and worldwide. We have the capabilities to provide the quality, power and speed to keep businesses optimized and running quickly over the internet. Our goal is to provide and connect thousands of clients around the world with a personalized hosting solution to meet the rising information technology demands of businesses. To learn more about Microsoft OWIN 3.0.1 Hosting, please visit http://asphostportal.com/ OWIN-Katana-ASPNET-Hosting

About ASPHostPortal.com :

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



FREE ASP.NET Hosting with ASPHostPortal.com :: How to Fix ASP.NET 4.0 has not been Registered on the Web Server Error

clock May 6, 2015 06:54 by author Dan

When making an ASP.NET website throughout IIS 7 in Visual Studio 2008/2010, you can find the following issue:

“ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly, Press F1 for more details”

This error usually occurs if you have installed IIS 7.x ‘after’ installing .NET. In order to resolve the error, do the following:

Step 1: Open Control Panel > Programs > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application development Feature

Check the box 'ASP.NET' . Also in the Web Management Tools, remember to select IIS 6 Management Compatibility and IIS Metabase as shown below.

Note: Make sure that you are running Visual Studio 2010 as Administrator.

Now run the site from Visual Studio 2010 using Ctrl + F5.

Step 2: If you further get the error “Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list” or Managed handler is used; however, ASP.NET is not installed or is not installed completely then do a Visual Studio 2010 repair.

Start > Programs > Accessories > Run. Type this command depending on the version of VS 2010 installed.

Silent Repair for 32-bit

%windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart


Silent Repair for 64-bit

%windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

That’s it. Restart IIS and the errors should be fixed.

Step 3: If the errors are not yet fixed, there could be an issue in the Application Pool. Follow these steps

1. Open IIS Manager (Run > Inetmgr) . Expand the server node and then click Application Pools

2. Now select the application pool that contains the application that you want to change. Go to Actions > View Applications.

3. Select the Application pool to change > In Action Pane, click on ‘Change Application Pool’

4. In the ‘Select Application Pool’ dialog box, select the application pool associated with .NET 4.0 from the Application pool list and then click OK.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Free ASP.NET Hosting with ASPHostPortal.com :: How to Using Facebook Graph API With ASP.NET MVC

clock April 20, 2015 05:52 by author Mark

This article series covers the use of the Facebook Graph API integration with an ASP.NET MVC web applications to learn how to incorporate Facebook features server-side.In this article series we will learn how to implement custom social media integration into our ASP NET web application using the Facebook SDK.
Here we will see in practical terms how to access and update Facebook data utilizing the Graph API.
Before we proceed let's see the few terms.

  • OAuth 2.0: Open standard for authorization

Provides secure delegate access specifically from Facebook as an OAuth provider. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials.

  • OWIN: Open Web Interface for .NET
  • Defines a standard interface between .NET web servers and web applications.
  • User Access Token: Encodes an App Id + User Id + Permissions
  • AppSecret_Proof: Encrypted Hash of the Access Token using App Secret key

So let's get started learning about Facebook Graph API integration.

Step 1: Open https://developers.facebook.com/ then click on My Apps and then add a new App as shown below.

Step 2: Select website and provide the Display name and namespace as shown below.
Here namespace is an alternative way to identify our application so don't confuse it with namespaces in C#.

Step 3: Click on settings and then click on Add Platform.

Step 4: Select website and we will get a couple of options as shown below.

Step 5: Now Let's create a test app which is best practice.

Summary

In this article we learn how to create a Facebook App. In the next article we will see how to authenticate with ASP.NET MVC applications.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Free ASP.NET Hosting with ASPHostPortal.com :: State Management in ASP.NET

clock April 15, 2015 05:53 by author Mark

State Management in ASP.NET

  • A new instance of the Web page class is created each time the page is posted to the server.
  • In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip.
  • The Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can be broadly divided into the following two categories:
    • Client-Side State Management Options
    • Server-Side State Management Options

Client-Side State Management

  • Client-based options involve storing information either in the page or on the client computer.
  • Some client-based state management options are:
    • Hidden fields
    • View state
    • Cookies
    • Query strings

Hidden Fields

  • A hidden field is a control similar to a TextBox control.
  • A hidden field does not render in a Web browser. A user cannot type anything into it.
  • Hidden fields can be used to store information that needs to be submitted along with the web page, but should not be displayed on the page.
  • Hidden fields can also be used to pass session information to and from forms, transparently.

To pass the information from one page to another, you can invoke the Server.Transfer method on the Click event of a Button control, as shown in the following example: 

protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("Page2.aspx");
    }

  • The target page can access the passed information by referring to individual controls on the source page, as shown in the following example: 

     String name = Request.Form["TextBox1"];
   String color = Request.Form["HiddenField1"];

View State

  • Each Web page and controls on the page have a property called ViewState.
  • This property is used to automatically save the values of the Web page and each control on the Web page prior to rendering the page.
  • The view state is implemented using a hidden form field called _VIEWSTATE.
  • This hidden form field is automatically created in every Web page.
  • When ASP.NET executes a Web page on the Web server, the values stored in the ViewState property of the page and controls on it are collected and formatted into a single encoded string.
  • The encoded string is:    
    • Assigned to the Value attribute of the hidden form field, _VIEWSTATE.
    • Sent to the client as part of the Web page.       
    • During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore the values in _VIEWSTATE.

Enabling and disabling view state

  • By default, the view state is enabled for a Web page and the controls on the Web page.
  • You can enable or disable view state for a page by setting the EnableViewState property of a Web page, as shown in the following example: 

<%@ Page Language="C#"AutoEventWireup="true"EnableViewState="false"CodeFile="Page1.aspx.cs"Inherits="Page1" %> 

  • You can enable or disable view state for a control by setting its EnableViewState property to false.
  • When view state is disabled for a page, the view state for the controls on the page is automatically disabled.

Cookies

  • Cookies
    • Cookies are: 
    • Used to store small pieces of information related to a user's computer such as its IP address, browser type, operating system, and Web pages last visited.
    • Sent to a client computer along with the page output.      

Types of cookies 

  • Temporary Cookies     
  • Exist in the memory space of a browser.
  • Also known as session cookies.
  • Are useful for storing information required for only a short time.         

Persistent Cookies     

  • Are saved as a text file in the file system of the client computer.
  • Are used when you want to store information for a longer period.
  • Are useful for storing information required for only a short time.      
  • Creating Cookies 

     Response.Cookies["userName"].Value = "Peter";
    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
    Reading Cookies

  • You can access the value of a cookie using the Request built-in object.   

    if (Request.Cookies["userName"].Value != null)
    {
        Label1.Text = Request.Cookies["userName"].Value;
    }

Query String

  • A query string: 
  • Provides a simple way to pass information from one page to another.
  • Is the part of a URL that appears after the question mark (?) character.    
  • You can pass data from one page to another page in the form of a query string using the Response.Redirect method, as shown in the following example:

Response.Redirect("BooksInfo.aspx?Category=fiction&Publisher=Sams");

Server-Side State Management

There are situations where you need to store the state information on the server side.
Server-side state management enables you to manage application-related and session-related information on the server.
ASP.NET provides the following options to manage state at the server side:

  • Application state
  • Session state
  • Application State

ASP.NET provides application state as a means of storing application-specific information such as objects and variables.
The following describes the information in the application state:

  • Is stored in a key-value pair.
  • Is used to maintain data consistency between server round trips and among pages.     
  • Application state is created the first time a user accesses any URL resource in an application.
  • After an application state is created, the application-specific information is stored in it. 

Storing and Reading information in application state

You can add application-specific information to an application state by creating variables and objects and adding them to the application state.
For example: 

Application ["MyVariable"] = "Hello";
You can read the value of MyVariable using the following code snippet:
stringval = (string) Application["MyVariable"];
  

Removing information from application state

  • You can remove an existing object or variable, such as MyVariable from an application state using the following code snippet:

Application.Remove(["MyVariable"]);

  • You can also remove all the application state variables and objects by using the following code snippet: 

Application.RemoveAll();  

Synchronizing application state

Multiple pages within an ASP.NET web application can simultaneously access the values stored in an application state, that can result in conflicts and deadlocks.
To avoid such situations, the HttpApplicationState class provides two methods, Lock() and Unlock().
These methods allow only one thread at a time to access application state variables and objects.

Session State

  • In ASP.NET, session state is used to store session-specific information for a web application.
  • The scope of session state is limited to the current browser session.
  • Session state is structured as a key-value pair for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
  • Session state is not lost if the user revisits a Web page by using the same browser window.

However, session state can be lost in the following ways: 

  • When the user closes and restarts the browser.
  • When the user accesses the same Web page in a different browser window.
  • When the session times out because of inactivity.
  • When the Session.Abandon() method is called within the Web page code.  
  • Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID string containing American Standard Code for Information Interchange (ASCII) characters.
  • You can store objects and variables in a session state.
  • You can add a variable, MyVariable with the value HELLO in the session state using the following code snippet:  

Session["MyVariable"]="HELLO";     

  • You can retrieve the value of the variable, MyVariable, using the following code snippet:  

String val = (string)Session["MyVariable"];

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASPHostPortal.com Announces Excellent Drupal 7.34 Hosting Solution

clock April 13, 2015 13:01 by author Dan

ASPHostPortal.com was established with the goal to provide high quality hosting services for everyone. They believe that providing high quality services should come at an affordable price. For this reason we have provided exceptional plans, at the lowest and free price, for the best services possible, on their fastest nodes ever. Today, they launch Drupal 7.34 hosting with high speed, full features, and FREE.

Drupal is an open source content management platform powering millions of websites and applications. It’s built, used, and supported by an active and diverse community of people around the world. With Drupal, marketers and web developers can create and manage great web, mobile and social experiences. And they can improve and adapt quickly thanks to ongoing innovation and ideas from the Drupal community.

Drupal now presents their new version (Drupal 7.34). Drupal 7.34 was released in response to the discovery of security vulnerabilities. ASPHostPortal offers a powerful Windows hosting platform which allows for easy to manage websites, FTP, email, and etc. Our hosting is housed in a state of the art data centre which gives a totally secure data protection and Super-Quick Network Access. With a knowledgeable support team available 24 hours a day, 7 days a week, you can rest assured that your Websites and Data are Secure and Available for your management anytime. To learn more about Drupal 7.34 Hosting, please visit http://asphostportal.com/Drupal-Hosting

About ASPHostPortal.com :
ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET

clock April 13, 2015 06:19 by author Ben

My previous article discussed about How Displaying Validation Errors with ASP.NET MVC. Now in this article, I’ve covered a brief introduction about How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET. There are lots of ways for Importing data from Excel to ASP.NET using C#, and here I’m going to introduce one simple common method to import data.

First we will create a new excel sheet with some data.

So for this article 1st I'll create a new asp.net application and add the beneath code inside your web page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Excel File Upload Or Import and Display In GridView Using C# In Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload & Display" OnClick="btnUpload_Click" />
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    <br />
    </form>
</body>
</html>

Now please check the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
                if (fileExtention == ".xls" || fileExtention == ".xlsx")
                {
                    string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPath("~/ExcelSheet/" + fileName));
                   /*Read excel sheet*/
                    string excelSheetFilename = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/ExcelSheet/" + fileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    OleDbConnection objcon = new OleDbConnection(excelSheetFilename);
                    string queryForExcel = "Select * from [UserDetail$];";
                    OleDbDataAdapter objda = new OleDbDataAdapter(queryForExcel, objcon);
                    DataSet objds = new DataSet();
                    objda.Fill(objds);
                    if (objds.Tables[0].Rows.Count > 0)
                    {
                        GridView1.DataSource = objds.Tables[0];
                        GridView1.DataBind();
                    }
                }
                else
                {
                    lblMessage.Text = "Please upload excel sheet.";
                }
            }
        }
    }
}

Now in above code I've very first read the file and saved inside a folder and also the I study the excel sheet and stored in dataset and bind it towards the gridview manage.

Now we will develop the folder.


Within this folder we'll upload the file as shown in code.

Now we've accomplished run the application and check the output.


Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: How Displaying Validation Errors with ASP.NET MVC

clock April 2, 2015 06:21 by author Ben

Today, I write about how Displaying Validation Errors with ASP.NET MVC. We all know how crucial it is to validate user input, but it’s equally crucial how we present validation errors for the user. Take the following type:


The e mail field needs to be optional but any address entered must be valid. If a validation error happens, it ought to replace the optional label using the error message.

Behind the scenes I’m employing Data Annotations to validate the email address, so any errors is going to be passed into the ModelState. MVC has built-in help for displaying these errors (using the ValidateMessageFor helper) so it is easy to create a wrapper around that, supplying the ‘optional’ text as a parameter.

Here’s an extension method for the HtmlHelper:

public static class ExtensionMethods
{
    public static MvcHtmlString HelpMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string helpText)
    {
        var validation = htmlHelper.ValidationMessageFor(expression);
        if (validation == null)
            return new MvcHtmlString("<span class='help-inline muted'>" + helpText + "</span>");
        else
            return validation;
    }
}

Here’s it’s usage:

<fieldset>
  <div class="control-group">
        @Html.LabelFor(x => x.EmailAddress, "Email", new { @class = "control-label" })
        <div class="controls">
            @Html.TextBoxFor(x => x.EmailAddress, new { @class = "input-xlarge", placeholder = "Enter an email address" })
            @Html.HelpMessageFor(x => x.EmailAddress, "Optional")
        </div>
    </div>
</fieldset>

Best ASP.NET MVC Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Data Annotations Validation in ASP.NET 4.5

clock March 18, 2015 06:28 by author Mark

Data Annotations Validation in ASP.NET

This article explains how to use data annotations for validation in ASP.Net 4.5. So, let's proceed with the following
The effect of a custom validation message: Required, String Length, Data Type, Range, Compare and Regular Expression.

Creating a Registration Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP.NET Web Forms Application". Name it "DataAnnotationsValidation".
seelct New ASP.NET Project then select the template Empty and select Web Forms then click OK.
Next, create the code-behind as follows, displaying the validation errors to the users in the Registration.aspx.

Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="DataAnnotationsValidation.Registration" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Employees Registration</title> 
    <link href="Content/bootstrap.min.css" rel="stylesheet" /> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div class="container"> 
            <div class="well"> 
                <h1>Data Annotations  Validation in ASP .NET 4.5 </h1> 
            </div> 
            <div class=" panel panel-default"> 
                <div class="panel-heading"> 
                    <h3 class="panel-title">Employees Registration</h3> 
                </div> 
                <div class="panel-body"> 
                    <div class="text-center"> 
                    <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true" DisplayMode="List" ForeColor="Red"  /> 
                    </div> 
                        <div class="col-md-8"> 
                            <div class="form-group col-lg-12"> 
                                <label>First Name</label> 
                                <asp:TextBox ID="FirstName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>Last Name</label> 
                                <asp:TextBox ID="LastName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>User ID</label> 
                                <asp:TextBox ID="UserID" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password </label> 
                                <asp:TextBox ID="Password" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password Confirm </label> 
                                <asp:TextBox ID="PasswordConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Mobile </label> 
                                <asp:TextBox ID="Mobile" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Age </label> 
                                <asp:TextBox ID="Age" runat="server" class="form-control"></asp:TextBox> 
                            </div>                             
                            <div class="form-group col-lg-6"> 
                                <label>Email </label> 
                                <asp:TextBox ID="Email" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Email Confirm </label> 
                                <asp:TextBox ID="EmailConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>DOB </label> 
                                <asp:TextBox ID="Date" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Salary </label> 
                                <asp:TextBox ID="Total" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>City </label> 
                                <asp:TextBox ID="HomeCity" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Department </label> 
                                 
                                <asp:DropDownList ID="Department" runat="server" class="form-control"> 
                        <asp:ListItem Value="">Choose an Option</asp:ListItem>
                        <asp:ListItem Value="HR">HR</asp:ListItem> 
                        <asp:ListItem Value="Account">Account</asp:ListItem> 
                                    </asp:DropDownList> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <asp:Button ID="btnsubmit" runat="server" Text="submit" /> 
                            </div> 
                        </div>                     
                </div> 
                </div> 
            </div> 
    </form> 
</body> 
</html>

Create DataAnnotationsValidation.Models for Validation
Now, do something with Models then click Add -> Class.
Applying validation attributes to the Validation class

Validation.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web;   
    //using Namespace 
    using System.ComponentModel.DataAnnotations; 
    namespace DataAnnotationsValidation.Models 
    { 
        public class Validation 
        {         
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string FirstName { get; set; }  
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string LastName { get; set; } 
            [Required] 
            [StringLength(25, MinimumLength = 3)] 
            public string UserID { get; set; } 
            [Required] 
            [DataType(DataType.Password)] 
            public string Password { get; set; } 
            [Required] 
            [Compare("Password")] 
            public string PasswordConfirm { get; set; } 
            [Required] 
            [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")] 
            public int Age { get; set; }   
            [Required]        
            [StringLength(10)] 
            public int Mobile { get; set; }           
            [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")] 
            public string Email { get; set; }     
            [Compare("Email")] 
            public string EmailConfirm { get; set; }    
            [Range(typeof(decimal), "0.00", "15000.00")] 
            public decimal Total { get; set; }   
            [Required] 
            [DataType(DataType.Date)] 
            public DateTime Date { get; set; }       
            [Required] 
            public string HomeCity { get; set; }      
            [Required] 
            public string Department { get; set; }     
        } 
    } 

Next, create the code-behind as follows.

Registration.aspx.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls;     
    //using Namespace Models 
    using System.Web.ModelBinding; 
    using DataAnnotationsValidation.Models;    
    namespace DataAnnotationsValidation 
    { 
        public partial class Registration : System.Web.UI.Page 
        { 
            protected void Page_Load(object sender, EventArgs e) 
            { 
                if (IsPostBack) 
                { 
                    Validation v = new Validation(); 
                    if (TryUpdateModel(v, new FormValueProvider(ModelBindingExecutionContext))) 
                    { 
                        ShowMessage(v.ToString());                     
                    } 
                } 
            } 
            /// <summary> 
            /// This function is used for show message. 
            /// </summary> 
            /// <param name="msg"></param> 
            void ShowMessage(string msg) 
            { 
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
            }     
        } 
    }

Now run the page, it will look like the following to use validation to check the input.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in