ASPHostDirectory Cheap .NET 4 Hosting

Blog about .NET Hosting and all its latest technology

ASPHostDirectory.com .NET 4 Hosting :: ASP.NET MVC 2 Render Template to String

clock July 14, 2010 11:08 by author Darwin

This topic contains information about key features and improvements in the ASP.NET MVC routing. This topic doesn’t provide comprehensive information about all new features and is subject to change. So, if you seek more information about ASP.NET MVC, you can choose ASPHostDirectory as alternatives. You’ll get the best service at an affordable price. Only with @ 3.99/month, you can directly get the services you want. So, what are you waiting for? Try it!!

In one of the projects that we are currently working on we have a lot of different emails we want to send out to users and we would like to build those emails from templates. Our goal was the leverage the existing ASP.NET view engine for this, but that turned out to be a lot more complicated than we had anticipated.


It turns out that because of issues with the core Page class, the WebFormViewEngine always renders directly to the Response. You can get around this by creating a fake HttpContext, but that seems like a really ugly hack. After some more searching we found some information on another method that involves getting a partial view as a standard WebForms Control and rendering it directly to a string.


We had to make a few tweaks to the code given in the above article to get the ViewData to populate properly. Here is what we came up with:


using System.IO;

using System.Text;

using System.Web.Mvc;

using System.Web.UI;


namespace MyProject.ClassLibrary.Utilities

{

    public class Template

    {

        /// <summary>

        /// Render a Partial View (MVC User Control, .ascx) to a string using the given ViewData.

        /// </summary>

        /// <param name="controlName"></param>

        /// <param name="viewData"></param>

        /// <returns></returns>

        public static string RenderPartialToString(string controlName, object viewData)

        {

            ViewDataDictionary vd = new ViewDataDictionary(viewData);

            ViewPage vp = new ViewPage { ViewData = vd };

            Control control = vp.LoadControl(controlName);


            vp.Controls.Add(control);


            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))

            {

                using (HtmlTextWriter tw = new HtmlTextWriter(sw))

                {

                    vp.RenderControl(tw);

                }

            }


            return sb.ToString();

        }

    }

}

You can now create a new template by adding a MVC 2 View User Control to your project (it should have the extension .ascx). The viewData object that you passed in is accessible through the ViewData.Model.

Here is a very simple example template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

This is a <em>simple</em> test email.

ViewData["test"] = <%: ((Dictionary<string, string>)ViewData.Model)["test"] %>


And you would render the template using:

Dictionary<string, string> viewData = new Dictionary<string, string>();

viewData["test"] = "This is a simple test string";

string output = MyProject.ClassLibrary.Utilities.Template.RenderPartialToString("~/Emails/TestEmail.ascx", viewData);

Ideally we should have been able to use the default MVC view engine to take care of this, but for now this method works well.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: Create a Database using Model-First Development

clock July 13, 2010 05:17 by author Darwin

Creating a Database using Model-First Development

Step 1: Create a new solution


1. Launch Visual Studio 2010 Beta 2.

2. Click the New Project link on the Start Page.  The New Project dialog box should appear.

3. Click on the Visual C# node from the tree view of installed templates.
4. Select Empty ASP.NET Web Application from the list of templates.
5. Enter OrderSystem for the project name and click the OK button.

Visual Studio will create a solution file in the folder you specified and also create a sub folder that contains the web site's project file and config files.

Step 2: Create an ADO.NET Entity Data Model

The next step is to create the ADO.NET Entity Data Model.  For this application we'll model the concept of users and addresses.  A user can have more that one address so we'll build an entity data model that models this relationship.

1. Right click on the OrderSystem project in the Solution Explorer and select Add à New Item…
2. Click the Data node under the Visual C# node in the Installed Templates tree.
3. Select the ADO.NET Entity Data Model template.
4. Change the name to OrderDB.edmx and click the Add button.
5. Visual Studio will display the Entity Data Model Wizard.  This is where you can decide to build the model from an existing database or create the model first and then build the database.
6. Choose Empty model from the wizard and click the Finish button.

Step 3: Create the Entities and Associations

The next step is to model the user and user's addresses relationship. Let's first create the user entity.

1. Right click on the Entity Data Model Designer and select AddàEntity… from the pop-up menu.
2. The Add Entity dialog box should appear.  Enter UserAccount for the Entity name.  Notice that as you type the Entity name the Entity Set name pluralizes the Entity name.  Think of the Entity name as the class that represents a record and the Entity set as the class that represents the table of those records.
3. By default the Entity Framework will create a Primary Key called Id.  If you wish to not create a primary key you can uncheck the Create key property checkbox from the dialog box.
4. Click the OK button. The UserAccount entity will be added to the entity diagram.
5. The next step is to add properties to this entity. Properties will map to fields in a table. We'll first add the First and Last name properties.
6. Right click on the UserAccount entity and select AddàScalar property from the pop-up menu.
7. Change the property name to FirstName.
8. In the properties window change the MaxLength to 50. Scalar properties are strings by default.
9. Add another property called LastName the same way and set its MaxLength to 50.

The next step is to add and insert date and update date properties.  We like to have the inserted and updated dates on every entity just for the sake of trouble shooting.  These are two properties that will be added to every entity so it is the perfect candidate for a Complex Type.  A Complex Type allows you to define a set of properties and then associate them with multiple entities.

10. In the Model Browser window, left click on the Complex Types nodes. 
11. Change the name of the complex type to AuditFields.
12. Right click on the AuditFields complex type in the Model Browser and select AddàScalar PropertyàDateTime from the pop-up menu.
13. Change the name to InsertDate.
14. Follow the same steps to add the UpdateDate property to the complex type.
15. Now you can add the Complex property to the UserAccount entity.  Right click the UserAccount entity and select AddàComplex Property from the pop-up menu.
16. Change the name to AuditFields.  The type should have already defaulted to AuditFields.

When the database is created from this entity it will contain the two audit fields defined in the complex type.

Now let's add the address entity.  A user can have more than one address so there is a one-to-many relationship between these two entities.

17. Right click the designer and select AddàEntity from the pop-up menu.
18. Change the name to Address and then click the OK button.
19. Add scalar properties to the Address entity for Address1, Address2, City, State, and Zip. 
20. Change Address2 to be nullable by settting the Nullable property to True in the properties window.  All other properties are required.
21. Now add the Audit Fields to this entity by right clicking the Address entity and selecting AddàComplex Property from the pop-up menu.  Set the name to AuditFields and the type to AuditFields.

The next step is to create an association between the UserAccount and Address entities.

22. Right click on the UserAccount entity and select AddàAssociation from the pop-up menu.
23. The Add Association dialog appears.  It assumes correctly that you want to create a one-to-many relationship between these two entities.  You use the Multiplicity drop down to define the variations of relationships but for this example you can leave the defaults and click the OK button.  Notice that a UserAccountId property was added to the Address table.

Step 4: Generate the Database

Now that the entities are defined we can create the database.  Visual Studio makes this quite simple.  A script is generated with the correct DDL statements to create tables, indexes, and relationships which you can then execute against your database

1. Right click on the Designer and select Generate Database from Model… from the pop-up menu.  The Generate Database Wizard will appear.
2. Click the New Connection… button.
3. Enter your server name.  Choose either User Windows Authentication or Use SQL Server Authentication. 
4. Enter OrderSystem for the name of the database and click the OK button.
5. You should get a message stating "The database 'OrderSystem' does not exist or you do not have permissions to see it.  Would you like to attempt to create it?"  Click the Yes button.
6. The database should be created and you'll be returned to the Generate Database Wizard dialog.  Click the Next button.
7. The wizard will now generate the DDL statements needed to create this database.
8. Click the Finish button.


Summary

That's all you need to do to create a database using the new Entity Framework's Model First methodology. This is a big improvement over the first edition because it allows you to use Visual Studio to work through the design of you objects first and then VS can figure out how to create the database tables, indexes, and relationships for you.

What is so SPECIAL on ASPHostDirectory.com ASP. Net 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in ASP. Net 4 Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: New Features in ASP.NET MVC 2.0

clock June 30, 2010 07:19 by author Darwin

Introduction

Microsoft's ASP.NET is a language and platform-neutral technology, arguably, one of the most successful web technologies ever. You can use it to design and develop web applications that can run on top of the managed environment of .NET Framework and inside the context of the IIS web server. Microsoft's MVC Framework is based on the time-tested and proven MVC Design Pattern and provides you a framework for building scalable, robust, high-performance web applications seamlessly. Applications designed using the MVC Design Pattern is easier to test and maintain. This article takes a look at the new features in ASP.NET MVC 2.0 and how one can leverage them in applications.

Getting Started with ASP.NET MVC 2.0

To work with ASP.NET MVC 2.0, you need to install it separately if you are using Microsoft Visual Studio 2008. Alternatively, you can use any one of the following versions of Microsoft Visual Studio 2010 - ASP.NET MVC Framework 2.0 is built-in.

Note that ASP.NET MVC Framework can be installed side by side with your ASP.NET MVC 1.0 and you can easily upgrade your ASP.NET MVC 1.0 applications to ASP.NET MVC 2.0 counterparts with ease. Moreover, Visual Studio 2010 has an built-in upgrade wizard that you can use to migrate your existing ASP.NET MVC 1.x applications to ASP.NET MVC 2.0 counterparts seamlessly. To migrate your old ASP.NET MVC 1.0 applications to ASP.NET MVC 2.0 applications manually, you should replace all occurences of "System.Web.Mvc, Version=1.0.0.0" with "System.Web.Mvc,Version=2.0.0.0", replace the old assemblies with newer ones, and also use bindingRedirect element in the web.config file of your ASP.NET MVC 1.0 application as shown below:

<runtime>

<assemblyBinding xmlns=

"urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="System.Web.Mvc"

publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0"

newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

Understanding the Model View Controller Design Pattern

The Model View Controller (or MVC as it is commonly called), is a proven design pattern that facilitates testability and easier maintenance of the application's code. It also promotes a cleaner separation of the application's concerns and is primarily based on the following major architectural components:

- The Model - the component that is responsible for storing the application's data and business logic components
- The View - the component responsible for invalidating the view based on the model's state and presenting the data to the user in the user interface
- The Controller - the component responsible for managing the interaction amongst these components

The primary advantage of this design pattern is easier maintenance, reduced cost and a cleaner isolation of the application's concerns.

What is the ASP.NET MVC Framework?

The ASP.NET MVC Framework is a framework from Microsoft that can be used to design and implement applications based on the MVC Design Pattern. The basic advantages of using the ASP.NET MVC Framework include: a cleaner separation of concerns, better code organization, extensibility, scalability and code reusability. It also provides an excellent support for a REST-based model and all existing ASP.NET features. As the ASP.NET MVC framework is built on top of the ASP.NET runtime, you can leverage the existing ASP.NET features like authentication and authorization, profile settings, localization, and so on.

Scott Guthrie states in his blog: "One of the benefits of using an MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated."

New Features in ASP.NET MVC Framework 2.0

ASP.NET MVC 2 is the new version of ASP.NET MVC Framework - a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) design pattern. Here is the list of the new features and enhancements in ASP.NET MVC Framework 2.0:

- Support for templated helpers - This is a new feature that you can use to associate templates with views for editing and displaying values based on a particular data type.

- Support for Asynchronous Controllers - You can now use controllers in ASP.NET MVC 2.0 applications to process requests asynchronously.

The abstract class AsyncController in the System.Web.Mvc namespace provides support for asynchronous operations for controller classes in ASP.NET MVC 2.0. Here is how this class looks like:

public abstract class AsyncController : Controller,

      IAsyncManagerContainer, IAsyncController, IController

The AsyncManager in the System.Web.Mvc.Async namespace provides support for asynchronous operations to the AsyncController class.

- Support for areas - You can use this new feature to partition and group functionalities in your ASP.NET MVC projects. This is a great new feature introduced in ASP.NET MVC 2.0. Areas enable you to organize ASP.NET MVC Applications to manage the complexity of large web applications seamlessly. In essence, an area is used to represent a section of a web site that is comprised of a group or a collection of related controllers, views, routes and sections. When you create a new area, Microsoft Visual Studio automatically adds a class that derives from AreaRegistration class to register the area and its routes. Here is an example:

namespace Test.Areas.Employee

   {

    public class EmployeeAreaRegistration : AreaRegistration

     {

        public override string AreaName

        {

            get { return "employee"; }

        }

 

        public override void RegisterArea(AreaRegistrationContext context)

        {

            context.MapRoute(

                "employee_default",

                "employee/{controller}/{action}/{id}",

                new { action = "Index", id = UrlParameter.Optional }

            );

 

            context.MapRoute(

                "employee_whatsnew",

                "whats-new",

                new { action = "WhatsNew", id = UrlParameter.Optional  }

            );

        }

    }

}

- Support for data annotations - You can use this feature to easily attach validation rules to the Model and View Model classes in your ASP.NET MVC applications.


- Support for strongly typed UI helpers - You can use this new feature to perform a compile-time check of the views. This feature also facilitates an enhanced Intellisense support for your view templates in an ASP.NET MVC application.

- Support for Templates and Templated Helpers - The introduction of templates is a major new feature in ASP.NET MVC Framework 2.0. Similar to Dynamic Data for WebForms, this is a feature that allows you to display or edit an object of a simple data or complex type. You can have the following types of templates in ASP.NET MVC Framework 2.0:

Default Template
Custom Object Template

Master Page Template

You can use Templated Helpers to create display and edit templates for various types. Templated Helpers enable you to have a compile time check and provide support for intellisense and code refactoring.


- Support for Client-Side Validation -

ASP.NET MVC 2.0 provides excellent support for client side validation. You can use attributes from the System.ComponentModel.DataAnnotations namespace. An an example, you can make a property or field mandatory using the [Required] attribute as shown in the code snippet below:

[Required]

public string FirstName { get; set;}

- The other attributes you can use include: Range, RegularExpression and StringLength

- Support for DefaultValueAttribute in Action-Method Parameters - This is yet another great new feature that allows you to pass default values as parameters to the action methods in your ASP.NET MVC 2.0 applications. Here is an example:

public class EmployeeController

{

  public ActionResult View(int id, [DefaultValue(1)]int pageNumber)

  {

 

  }

}


Summary

If you’re looking for ASP.NET MVC hosting, you can always consider ASPHostDirectory as the alternatives. You can start from only $ 3.99/month to get ASP.NET MVC hosting.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: .Views and UI Rendering in MVC Applications

clock June 15, 2010 07:44 by author Darwin

The ASP.NET MVC framework supports the use of a view engine to generate views (UI). By default, the MVC framework uses custom types (ViewPage, ViewMasterPage, and ViewUserControl) that inherit from the existing ASP.NET page (.aspx), master page (.master), and user control (.ascx) types as views.

In the typical workflow of an MVC Web application, controller action methods handle an incoming Web request. These action methods use the incoming parameter values to execute application code and to retrieve or update data model objects from a database. The methods then select a view that renders a response to a browser.

If you’re looking for ASP.NET MVC hosting, you can always consider ASPHostDirectory as the alternatives. Only with $ 3.99/month, you can get the professional ASP.NET MVC hosting. So, what are you waiting for?

Rendering UI with Views

In the Model-View-Controller (MVC) pattern, views are intended exclusively for encapsulating presentation logic. They should not contain any application logic or database retrieval code. All application logic should be handled by the controller. A view renders the appropriate UI by using the data that is passed to it from the controller. This data is passed to a view from a controller action method by using the View method.

The following example shows how a view is rendered in a controller class.

Public Function Categories()

    Dim categories As List(Of Category) = northwind.GetCategories()

    Return View(categories)

End Function

In the example, the parameter that is passed in the View method call is a list of Category objects that are passed to the view. The View method calls the view engine, which uses the data in the list to render to the view and to display it in the browser.

View Pages

A view page is an instance of the ViewPage class. It inherits from the Page class and implements the IViewDataContainer interface. The ViewPage class defines a ViewData property that returns a ViewDataDictionary object. This property contains the data that the view should display.

You can create a view page by using templates that are provided in a Visual Studio project for an ASP.NET Web application. By default, views are ASP.NET Web pages that are rendered by the MVC framework. The MVC framework uses URL routing to determine which controller action to invoke, and the controller action then decides which views to render.

The following example shows the markup for the Index.aspx page. This page is one of the default views that is generated when you create a new MVC project in Visual Studio. By convention, the name "Index" is given to the default view for an ASP.NET MVC application.

<h2><%= Html.Encode(ViewData("Message")) %></h2>

<p>

    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.

</p>

The @ Page directive contains the Inherits attribute, which defines the relationship between the application and the view. By default, the value of the Inherits attribute uses the following pattern: Application.Views.Controller.ViewPage

If you are working with a strongly typed view, the Inherits attribute uses the following pattern:

Application.Views.Controller.ViewPage<Type>

Master-Page Views

Like ASP.NET pages in Web Forms-based applications, ASP.NET page views (.aspx files) can use master pages to define a consistent layout and structure. In a typical site, the master page is bound to a content page in the @ Page directive of the content page. You can also use dynamic master pages (that is, you can assign a master page at run time) when you call the View method of the Controller class.

The following example shows the Site.master view, which is the master page that is generated when you create a new MVC project in Visual Studio.

<%@ Master Language="VB" Inherits="System.Web.Mvc.ViewMasterPage" %>

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>

    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

</head>

 
<body>

    <div class="page">

 
       
<div id="header">

            <div id="title">

                <h1>My MVC Application</h1>

            </div>

 
           
<div id="logindisplay">

                <% Html.RenderPartial("LogOnUserControl")%>               

            </div>

 
           
<div id="menucontainer">

 
               
<ul id="menu">             

                    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>

                    <li><%=Html.ActionLink("About", "About", "Home")%></li>

                </ul>

 
           
</div>

        </div>

 
       
<div id="main">

            <asp:ContentPlaceHolder ID="MainContent" runat="server" />

 
           
<div id="footer">

            </div>

        </div>

    </div>

</body>

</html>

Partial Views

A partial view enables you to define a view that will be rendered inside a parent view. Partial views are implemented as ASP.NET user controls (.ascx).

When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view. The partial view therefore has access to the data of the parent view. However, if the partial view updates the data, those updates affect only the partial view's ViewData object. The parent view's data is not changed.

Helper Classes and Members for Rendering Views

When you create views, many tasks are repetitive or require special MVC framework knowledge. To address these scenarios and to make it easier to render HTML, the MVC framework includes helper classes and members. The design for helper classes is extensible so that you can add custom helper classes and members.

The MVC framework includes the following helpers:

- Form helpers, which are for form elements such as radio buttons, list boxes, select buttons, text boxes, text areas, hidden content, and password fields.
- URL helpers, which let you generate URLs for routing.
- HTML helpers, which include functions to manage HTML strings, such as Encode, Decode, AttributeEncode, and RenderPartial.

You can access code-based rendering helpers by using properties that are added to the ViewPage, ViewUserControl, and ViewMasterPage classes.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: Validating with a Service Layer (VB)

clock June 8, 2010 06:12 by author Darwin

The goal of this tutorial is to describe one method of performing validation in an ASP.NET MVC application. In this tutorial, you learn how to move your validation logic out of your controllers and into a separate service layer. If you’re looking for ASP.NET MVC hosting, you can choose ASPHostDirectory as the alternatives. Only with $ 3.99/month, you can get this application. So, what are you waiting for?

Separating Concerns

When you build an ASP.NET MVC application, you should not place your database logic inside your controller actions. Mixing your database and controller logic makes your application more difficult to maintain over time. The recommendation is that you place all of your database logic in a separate repository layer.

For example, Listing 1 contains a simple repository named the ProductRepository. The product repository contains all of the data access code for the application. The listing also includes the IProductRepository interface that the product repository implements.

Listing 1 - Models\ProductRepository.vb

Public Class ProductRepository

      Implements IProductRepository
     

    Private _entities As New ProductDBEntities()


      Public Function ListProducts() As IEnumerable(Of Product) Implements IProductRepository.ListProducts

            Return _entities.ProductSet.ToList()

      End Function


      Public Function CreateProduct(ByVal productToCreate As Product) As Boolean Implements IProductRepository.CreateProduct

            Try

                  _entities.AddToProductSet(productToCreate)

                  _entities.SaveChanges()

                  Return True

            Catch

                  Return False

            End Try

      End Function


End Class

Public Interface IProductRepository

      Function CreateProduct(ByVal productToCreate As Product) As Boolean

      Function ListProducts() As IEnumerable(Of Product)

End Interface

The controller in Listing 2 uses the repository layer in both its Index() and Create() actions. Notice that this controller does not contain any database logic. Creating a repository layer enables you to maintain a clean separation of concerns. Controllers are responsible for application flow control logic and the repository is responsible for data access logic.

Listing 2 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller
     

    Private _repository As IProductRepository

      Public Sub New()

            Me.New(New ProductRepository())

      End Sub


      Public Sub New(ByVal repository As IProductRepository)

            _repository = repository

      End Sub


      Public Function Index() As ActionResult

            Return View(_repository.ListProducts())

      End Function


      '

      ' GET: /Product/Create

      Public Function Create() As ActionResult

            Return View()

      End Function

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude:="Id")> ByVal productToCreate As Product) As ActionResult

            _repository.CreateProduct(productToCreate)

            Return RedirectToAction("Index")

      End Function


End Class

Creating a Service Layer

So, application flow control logic belongs in a controller and data access logic belongs in a repository. In that case, where do you put your validation logic? One option is to place your validation logic in a service layer.

A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic.

For example, the product service layer in Listing 3 has a CreateProduct() method. The CreateProduct() method calls the ValidateProduct() method to validate a new product before passing the product to the product repository.

Listing 3 - Models\ProductService.vb

Public Class ProductService

      Implements IProductService

      Private _modelState As ModelStateDictionary

      Private _repository As IProductRepository

      Public Sub New(ByVal modelState As ModelStateDictionary, ByVal repository As IProductRepository)

            _modelState = modelState

            _repository = repository

      End Sub

      Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean

            If productToValidate.Name.Trim().Length = 0 Then

                  _modelState.AddModelError("Name", "Name is required.")

            End If

            If productToValidate.Description.Trim().Length = 0 Then

                  _modelState.AddModelError("Description", "Description is required.")

            End If

            If productToValidate.UnitsInStock

The Product controller has been updated in Listing 4 to use the service layer instead of the repository layer. The controller layer talks to the service layer. The service layer talks to the repository layer. Each layer has a separate responsibility.

Listing 4 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller

      Private _service As IProductService

      Public Sub New()

            _service = New ProductService(Me.ModelState, New ProductRepository())

      End Sub

      Public Sub New(ByVal service As IProductService)

            _service = service

      End Sub


      Public Function Index() As ActionResult

            Return View(_service.ListProducts())

      End Function


      '

      ' GET: /Product/Create

 

      Public Function Create() As ActionResult

            Return View()

      End Function

 

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult

            If Not _service.CreateProduct(productToCreate) Then

                  Return View()

            End If

            Return RedirectToAction("Index")

      End Function


End Class

Notice that the product service is created in the product controller constructor. When the product service is created, the model state dictionary is passed to the service. The product service uses model state to pass validation error messages back to the controller.

Decoupling the Service Layer

We have failed to isolate the controller and service layers in one respect. The controller and service layers communicate through model state. In other words, the service layer has a dependency on a particular feature of the ASP.NET MVC framework.

We want to isolate the service layer from our controller layer as much as possible. In theory, we should be able to use the service layer with any type of application and not only an ASP.NET MVC application. For example, in the future, we might want to build a WPF front-end for our application. We should find a way to remove the dependency on ASP.NET MVC model state from our service layer.

In Listing 5, the service layer has been updated so that it no longer uses model state. Instead, it uses any class that implements the IValidationDictionary interface.

Listing 5 - Models\ProductService.vb (decoupled)

Public Class ProductService

      Implements IProductService

      Private _validatonDictionary As IValidationDictionary

      Private _repository As IProductRepository

      Public Sub New(ByVal validationDictionary As IValidationDictionary, ByVal repository As IProductRepository)

            _validatonDictionary = validationDictionary

            _repository = repository

      End Sub

      Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean

            If productToValidate.Name.Trim().Length = 0 Then

                  _validatonDictionary.AddError("Name", "Name is required.")

            End If

            If productToValidate.Description.Trim().Length = 0 Then

                  _validatonDictionary.AddError("Description", "Description is required.")

            End If

            If productToValidate.UnitsInStock

The IValidationDictionary interface is defined in Listing 6. This simple interface has a single method and a single property.

Listing 6 - Models\IValidationDictionary.cs

Public Interface IValidationDictionary

      Sub AddError(ByVal key As String, ByVal errorMessage As String)

      ReadOnly Property IsValid() As Boolean

End Interface

The class in Listing 7, named the ModelStateWrapper class, implements the IValidationDictionary interface. You can instantiate the ModelStateWrapper class by passing a model state dictionary to the constructor.

Listing 7 - Models\ModelStateWrapper.vb

Public Class ModelStateWrapper

      Implements IValidationDictionary

      Private _modelState As ModelStateDictionary

      Public Sub New(ByVal modelState As ModelStateDictionary)

            _modelState = modelState

      End Sub

      #Region "IValidationDictionary Members"

      Public Sub AddError(ByVal key As String, ByVal errorMessage As String) Implements IValidationDictionary.AddError

            _modelState.AddModelError(key, errorMessage)

      End Sub

      Public ReadOnly Property IsValid() As Boolean Implements IValidationDictionary.IsValid

            Get

                  Return _modelState.IsValid

            End Get

      End Property

      #End Region

End Class

Finally, the updated controller in Listing 8 uses the ModelStateWrapper when creating the service layer in its constructor.

Listing 8 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller

      Private _service As IProductService

      Public Sub New()

            _service = New ProductService(New ModelStateWrapper(Me.ModelState), New ProductRepository())

      End Sub

      Public Sub New(ByVal service As IProductService)

            _service = service

      End Sub


      Public Function Index() As ActionResult

            Return View(_service.ListProducts())

      End Function


      '

      ' GET: /Product/Create

      Public Function Create() As ActionResult

            Return View()

      End Function

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult

            If Not _service.CreateProduct(productToCreate) Then

                  Return View()

            End If

            Return RedirectToAction("Index")

      End Function


End Class

Using the IValidationDictionary interface and the ModelStateWrapper class enables us to completely isolate our service layer from our controller layer. The service layer is no longer dependent on model state. You can pass any class that implements the IValidationDictionary interface to the service layer. For example, a WPF application might implement the IValidationDictionary interface with a simple collection class.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: How to Create a DropDownList with ASP.NET MVC

clock June 1, 2010 05:21 by author Darwin

This topic contains information about key features and improvements in the ASP.NET MVC. This topic doesn’t provide comprehensive information about all new features and is subject to change. So, if you seek more information about ASP.NET MVC, you can choose ASPHostDirectory as alternatives. You’ll get the best service at an affordable price. Only with @ 3.99/month, you can directly get the services you want. So, what are you waiting for? Try it!!

Standard Html Helpers

One of the cool features of ASP.NET MVC is the automatic binding of html form fields: all the Html helper methods will auto-magically take the default value of the form field directly from the ViewData or the view model object with the same name of the control.

Calling the TextBox helper method:

<%= Html.TextBox("Name") %>

will results, if the view model supplied contained the property Name, in the following HTML:

<input id="Name" name="Name" type="text" value="Simone" />

It would have been the same as calling the other helper overload, which specifies both the name and the value:

<%= Html.TextBox("Name", Model.Name) %>


Introducing the DropDownList helper


But things get a bit more complex when it comes to the HTML Select element, which most ASP.NET developers know as DropDownList. This control needs two values to be retrieved from the ViewData: the list of items to be displayed in the drop down, and the item that needs to be pre-selected, so the code to set it up is a bit more complex.

The automatic binding of the other html helpers still works but, since it can bind only one thing at the time, depending on your preferences you have and the scenario you are facing, you have to decide whether you want to automatically bind the list item or the selected item.

The method signature

Let’s have a look at the method signature:

Html.DropDownList(
    string name,
    IEnumerable<SelectListItem> selectList,
    string optionLabel,
    object htmlAttributes)


and the meaning of the parameters:
- name – the name of the HTML select element, and also the name of the view model property that is bound to the element
- selectList – the list of options of the select list
- optionLabel – the text that will be added at the top of the select list. Usually something like “Select …”
- htmlAttributes – this is in common with all the other html helper. A dictionary or an anonymous type with the html attributes you want to add to the HTML element

All the parameters except the first one are optional: if only the name is provided, the helper will automatically bind the list item. Otherwise if both the name and selectList are provided, the select item will be bound, and the select list will be the one supplied with the parameter. You’ll see how to adopt each approach later.


The SelectListItemClass


But now let’s have a look at the presentation model class used to represent the drop down list with its options: SelectListItem.

This class has three properties:
- string Text – the string that will be displayed as text of the option
- string Value – the string that will be used as the value of the option
- bool Selected – whether the option is selected

How to write a DropDownList

Let’s now have a look at the two possible way of building a DropDownList.


Autobinding the ItemList

The first approach consists in setting up the whole list of items in the controller, specifying also which options must be the selected item.

List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
        {
          Text = "Swimming",
          Value = "1"
        });
items.Add(new SelectListItem
        {
            Text = "Cycling",
            Value = "2",
            Selected = true
        });
items.Add(new SelectListItem
        {
            Text = "Running",
            Value = "3"
        });

As you can see, you set the text and value for each option, and set Selected = true for the item you want to be selected. And then you call the helper, specifying only the name: this will be the name of the select element, and must be the same name of the property of the view model that contains the list of items (in the sample named ListItems).

<%= Html.DropDownList("ListItems") %>

But in case you are caching the list of items or are retrieving them separately from the item that must be selected this is not the best solution.

Autobinding the selected item

The other approach is to automatically bind the selected item, and passing the list of items as parameter to the DropDownList helper method.

In the controller you do exactly the same thing as before, just don’t set to true the Selected property of any item. Then you also have to put into the view model the value of the item you want to select.
var model = new IndexViewModel()
        {
            ListItems = items,
            SelectedItem = 2
        };

And finally in the view, you use the overload which accepts also the selectList parameter:

<%= Html.DropDownList("SelectedItem", Model.ListItems) %>

The only difference in the HTML rendered is that, with first approach, the name of the HTML select element is “ListItems”, with the second it is “SelectedItem”.

These approaches are fine if you are creating your own list, but they are not the optimal solution if you are receiving the list of options for an external method, for example from a DB repository.

Using the SelectList helper class

To address the latest scenario the ASP.NET MVC framework comes with a class that helps you build the list of items in a way that can be accepted by the DropDownList html helper: it’s called SelectList.

This class encapsulates all the information needed to create a list of SelectListItem:
- Items – any IEnumerable containing the list of items that needs to be in the select element
- DataTextField and DataValueField – the names of the properties that will be used as text and as value of the item
- SelectedValue – the value of the selected item

Using this you can take any list of objects and turn it into a list of SelectListItem

//with selected value specified

var selectItems = new SelectList(brands, "BrandId", "BikeBrand", 2);

//only the items list

var selectItems = new SelectList(brands, "BrandId", "BikeBrand");

And you can use it either specifying the selected value in the controller, and using the overload with just the name parameter, or specifying the selected value as additional property in the view model and using the overload that takes both the name and the selectList property (same as the first two approaches).

Wrapping up


In this post we dissected the DropDownList API, and you saw the different possible approaches to writing a dropdown list:

- Specifying all the info needed (list of options and selected option) inside a List of SelectListItem and passing it to view: this is a good solution if you build the list and you can set the selected item at the same time and in the same process
- Put the list of options as a List of SelectListItem and the Selected Item in two separate properties of the view model: this approach is better if you build the list and retrieve the selected item in different moment and/or in different processes
- Use the SelectList helper class to create the needed list: use this approach if you receive the list of items for a external library and you don’t want to manually cycle over it to create the List of SelectListItem

Hope this post helped clearing up a bit the confusion that we saw around the DropDownList helper method.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET Hosting :: Using the TagBuilder Class to Create HTML Helpers (VB)

clock May 30, 2010 07:08 by author Darwin

This topic contains brief information about ASP.NET MVC. This topic doesn’t provide comprehensive information about all new features and is subject to change. So, if you seek more information about ASP.NET MVC, you can choose ASPHostDirectory as alternatives. You’ll get the best service at an affordable price. Only with @ 3.99/month, you can directly get the services you want. So, what are you waiting for? Try it!!

The ASP.NET MVC framework includes a useful utility class named the TagBuilder class that you can use when building HTML helpers. The TagBuilder class, as the name of the class suggests, enables you to easily build HTML tags. In this brief tutorial, you are provided with an overview of the TagBuilder class and you learn how to use this class when building a simple HTML helper that renders HTML <img> tags.

Overview of the TagBuilder Class

The TagBuilder class is contained in the System.Web.Mvc namespace. It has five methods:

- AddCssClass() – Enables you to add a new class=”” attribute to a tag.
- GenerateId() – Enables you to add an id attribute to a tag. This method automatically replaces periods in the id (by default, periods are replaced by underscores)
- MergeAttribute() – Enables you to add attributes to a tag. There are multiple overloads of this method.
- SetInnerText() – Enables you to set the inner text of the tag. The inner text is HTML encode automatically.
- ToString() – Enables you to render the tag. You can specify whether you want to create a normal tag, a start tag, an end tag, or a self-closing tag.

The TagBuilder class has four important properties:

- Attributes – Represents all of the attributes of the tag.
- IdAttributeDotReplacement – Represents the character used by the GenerateId() method to replace periods (the default is an underscore).
- InnerHTML – Represents the inner contents of the tag. Assigning a string to this property does not HTML encode the string.
- TagName – Represents the name of the tag.

These methods and properties give you all of the basic methods and properties that you need to build up an HTML tag. You don’t really need to use the TagBuilder class. You could use a StringBuilder class instead. However, the TagBuilder class makes your life a little easier.


Creating an Image HTML Helper

When you create an instance of the TagBuilder class, you pass the name of the tag that you want to build to the TagBuilder constructor. Next, you can call methods like the AddCssClass and MergeAttribute() methods to modify the attributes of the tag. Finally, you call the ToString() method to render the tag.

For example, Listing 1 contains an Image HTML helper. The Image helper is implemented internally with a TagBuilder that represents an HTML <img> tag.

Listing 1 – Helpers\ImageHelper.vb

Public Module ImageHelper

      <System.Runtime.CompilerServices.Extension> _

      Function Image(ByVal helper As HtmlHelper, ByVal id As String, ByVal url As String, ByVal alternateText As String) As String

            Return Image(helper, id, url, alternateText, Nothing)

      End Function

      <System.Runtime.CompilerServices.Extension> _

      Function Image(ByVal helper As HtmlHelper, ByVal id As String, ByVal url As String, ByVal alternateText As String, ByVal htmlAttributes As Object) As String

            ' Create tag builder

            Dim builder = New TagBuilder("img")

            ' Create valid id

            builder.GenerateId(id)

            ' Add attributes

            builder.MergeAttribute("src", url)

            builder.MergeAttribute("alt", alternateText)

            builder.MergeAttributes(New RouteValueDictionary(htmlAttributes))

            ' Render tag

            Return builder.ToString(TagRenderMode.SelfClosing)

      End Function

End Module

The module in Listing 1 contains two overloaded methods named Image(). When you call the Image() method, you can pass an object which represents a set of HTML attributes or not.

Notice how the TagBuilder.MergeAttribute() method is used to add individual attributes such as the src attribute to the TagBuilder. Notice, furthermore, how the TagBuilder.MergeAttributes() method is used to add a collection of attributes to the TagBuilder. The MergeAttributes() method accepts a Dictionary<string,object> parameter. The The RouteValueDictionary class is used to convert the Object representing the collection of attributes into a Dictionary<string,object>.

After you create the Image helper, you can use the helper in your ASP.NET MVC views just like any of the other standard HTML helpers. The view in Listing 2 uses the Image helper to display the same image of an Xbox twice (see Figure 1). The Image() helper is called both with and without an HTML attribute collection.

Listing 2 – Home\Index.aspx

<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<%@ Import Namespace="MvcApplication1" %>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

    <!-- Calling helper without HTML attributes -->

    <%= Html.Image("img1", ResolveUrl("~/Content/XBox.jpg"), "XBox Console") %>

    <!-- Calling helper with HTML attributes -->

    <%= Html.Image("img1", ResolveUrl("~/Content/XBox.jpg"), "XBox Console", New With {.border="4px"})%>


</asp:Content>

Notice that you must import the namespace associated with the Image helper at the top of the Index.aspx view. The helper is imported with the following directive:

<%@ Import NameSpace=”MvcApplication1” %>

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com .NET 4 Hosting :: Localizing ASP.NET MVC Validation

clock May 24, 2010 08:09 by author Darwin

In our recent post on custom validation with ASP.NET MVC 2, several people asked about how to localize validation messages. They didn’t want their error messages hard-coded as an attribute value.

It turns out that it’s pretty easy to do this. Localizing error messages is not specific to ASP.NET MVC, but is a feature of Data Annotations and ASP.NET. And everything we cover here works for ASP.NET MVC 1.0 (except for the part about client validation which is new to ASP.NET MVC 2).

Let’s start with the
ProductViewModel

public class ProductViewModel {

  [Price(MinPrice = 1.99)]

  public double Price { get; set; }

 

  [Required]

  public string Title { get; set; }

}

If we’re going to localize the error messages for the two properties, we need to add resources to our project. To do this, right click on your ASP.NET MVC project and select Properties. This should bring up the properties window. Click on the Resources tab. You’ll see a message that says,

This project does not contain a default resources file. Click here to create one.


Obey the message. After you click on the link, you’ll see the resource editor. Make sure to change the Access Modifier to Public (it defaults to Internal). Now enter your resource strings in the resource file.

The next step is to annotate the model so that it pulls the error messages from the resources.

public class ProductViewModel {

  [Required(ErrorMessageResourceType = typeof(Resources),

    ErrorMessageResourceName = "Required")]

  public string Title { get; set; }

  [Price(MinPrice = 3.99, ErrorMessageResourceType = typeof(Resources),

    ErrorMessageResourceName = "PriceIsNotRight")]

  public double Price { get; set; }

}

For the ErrorMessageResourceType, We just specify the type created by the build provider. In our case, the full type name is CustomValidationAttributeWeb.Properties.Resources.

Now, you can try it..
Happy Programming!!


What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!