ASPHostDirectory.COM Cheap ASP.NET MVC Hosting

Blog about ASP.NET MVC Hosting and its Technology

ASPHostDirectory ASP.NET MVC Hosting :: Create ASP.NET MVC Localization with Language Detection

clock October 22, 2010 06:06 by author Darwin

Introduction

In this tutorial we will show a simple way to create localization (globalization) for web application using APS.NET MVC framework. It should work fine with MVC 1 and 2 and were currently using .NET 3.5 SP1, but .NET 4.0 will work as well. All code is in C# and for language translations we use XML files.

Language files with XML

For translations of different languages we use simple xml files. We store them in App_Data/messages/<locale>.xml, for example en-US.xml or de-DE.xml. Here is the xml structure:

<items>
  <item key="home">Home</item>
  <item key="products">Products</item>
  <item key="services">Services</item>
</items>

You should have identical language files for all desired languages. All translation items should be the same (with equal “key” attributes).

Create Translator class

Main translation work will be done by Translator singleton class. Create “Infrastructure” folder in your MVC project and put class Translator there.
First, let’s make class singleton:

private static Translator instance = null;
public static Translator Instance
{
    get
    {
        if (instance == null)
        {
            instance = new Translator();
        }
        return instance;
    }
}
private Translator() { }

Add the following fields and properties to the class:

private static string[] cultures = { "en-US", "bg-BG" };
private string locale = string.Empty;

public string Locale
{
    get
    {
        if (string.IsNullOrEmpty(locale))
        {
            throw new Exception("Locale not set");
        }
        else
        {
            return locale;
        }
    }
    set
    {
        if (Cultures.Contains(value))
        {
            locale = value;
            load();
        }
        else
        {
            throw new Exception("Invalid locale");
        }
    }
}

public static string[] Cultures
{
    get
    {
        return cultures;
    }
}

Field "cultures" lists available cultures. "Locale" keeps current culture. And in "set" part of Locale property you can see invocation of load() method. We will talk about it later.
To keep localization data I will create simple dictionary and then use keys from XML for dictionary keys and XML item values as dictionary values. Simple Translate method will do translation job. We have indexer method for easy access.

private Dictionary data = null;

public string Translate(string key)
{
    if (data != null && data.ContainsKey(key))
    {
        return data[key];
    }
    else
    {
        return ":" + key + ":";
    }
}

public string this[string key]
{
    get
    {
        return Translate(key);
    }
}

If some key cannot be found and translated, we return the key with ":" around it, so you can easy find untranslated items.
Finally, for loading XML we use LINQ to XML. we have static caching dictionary, so I don't need reading XML on every request.

private static Dictionary<string, Dictionary<string, string>> cache =
  new Dictionary<string, Dictionary<string, string>>();

private void load()
{
    if (cache.ContainsKey(locale) == false) // CACHE MISS !
    {
        var doc = XDocument.Load(
            HttpContext.Current.Server.MapPath(
               "~/App_Data/messages/" + locale + ".xml"));

        cache[locale] = (from item in doc.Descendants("item")
                         where item.Attribute("key") != null
                         select new
                         {
                             Key = item.Attribute("key").Value,
                             Data = item.Value,
                         }).ToDictionary(i => i.Key, i => i.Data);
    }

    data = cache[locale];
}

public static void ClearCache()
{
    cache = new Dictionary<string, Dictionary<string, string>>();
}

You can use translator in your controller like this:
Translator.Instance[key];
After load() methid we have ClearCache method for easy developing (you know, once read, data is cached and you have to restart IIS Application Pool to refresh localization data).
Translator class is ready, we will show you how to use it later.

Create localization helpers

Create static class LocalizationHelpers and put it in "Helpers" folder in your project.

public static string CurrentCulture(this HtmlHelper html)
{
    return Translator.Instance.Locale;
}

public static string T(this HtmlHelper html, string key)
{
    return html.Encode(Translator.Instance[key]);
}

public static string T(this HtmlHelper html, string key,
    params object[] args)
{
    return html.Encode(string.Format(
        Translator.Instance[key], args));
}

We will use this in html views for translation like this

<%= Html.T("products") %>

If you want params in translated values you can use second T implementation like string.Format. First helper CurrentCulture is used in language select user control to determine current culture.

Create BaseController class

Create BaseController class that extends Controller and put it in "Infrastructure" folder of your MVC project. You should extend all your controller classes from this class. Create simple property for current selected culture (locale)

public string CurrentCulture
{
    get
    {
        return Translator.Instance.Locale;
    }
}

You will use this in your controller when you initialize your model, for example.
In the following code I will explain language detection and saving with cookie.

private void initCulture(RequestContext requestContext)
{
    string cultureCode = getCulture(requestContext.HttpContext);

    requestContext.HttpContext.Response.Cookies.Add(
        new HttpCookie("Culture", cultureCode)
        {
            Expires = DateTime.Now.AddYears(1),
            HttpOnly = true,
        }
    );

    Translator.Instance.Locale = cultureCode;

    CultureInfo culture = new CultureInfo(cultureCode);
    System.Threading.Thread.CurrentThread.CurrentCulture = culture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

private string getCulture(HttpContextBase context)
{
    string code = getCookieCulture(context);

    if (string.IsNullOrEmpty(code))
    {
        code = getCountryCulture(context);
    }

    return code;
}

private string getCookieCulture(HttpContextBase context)
{
    HttpCookie cookie = context.Request.Cookies["Culture"];

    if (cookie == null || string.IsNullOrEmpty(cookie.Value) ||
         !Translator.Cultures.Contains(cookie.Value))
    {
        return string.Empty;
    }

    return cookie.Value;
}

private string getCountryCulture(HttpContextBase context)
{
    // some GeoIp magic here
    return "en-US";
}

First we try to get language cookie if there is any (if this is not first time visit). If there is no cookie you can detect browser language, make GeoIP IP address lookup and so on. After finding some valid locale/culture we set response cookie for next page visits. After this we change current thread culture. This is useful if you want to format some date or currency values.
You should call initCulture in overridden Initialize method.

Changes in HomeController

Don't forget to change parent class of all your controller to BaseController. Add following code to your HomeController, so you can change current culture. When you open specified URL, a cookie is set and user is redirected to index page. This URL is like example.com/home/culture/en-US. Clear cache method is for deleting current cache without restarting application pool. Access it with example.com/home/ClearLanguageCache

public ActionResult Culture(string id)
{
    HttpCookie cookie = Request.Cookies["Culture"];
    cookie.Value = id;
    cookie.Expires = DateTime.Now.AddYears(1);
    Response.SetCookie(cookie);

    return Redirect("/");
}

public ActionResult ClearLanguageCache(string id)
{
    Translator.ClearCache();

    return Redirect("/");
}

To change current language we will create special user control which will be included in may Master.Site layout. Create CultureUserControl.ascx and put it in Views/Shared/ folder of your MVC project. Here is the code:

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

<% if (Html.CurrentCulture() == "bg-BG") { %>
    <a id="lang" href="/home/culture/en-US">en</a>
<% } else { %>
    <a id="lang" href="/home/culture/bg-BG">bg</a>
<% } %>

In our layout we use <% Html.RenderPartial("CultureUserControl"); %> to include it.

Conclusion

In this simple tutorial we've created localization infrastructure for ASP.NET MVC web application. Translations of different languages are stored in XML files. Then we use Translator class to load them. Current user culture is kept in cookie. You can access Translator class in html views using some helpers. Also all the translation data we cached so it will not be loaded form XML every request.
Hope this tutorial helps.

What is so SPECIAL on ASPHostDirectory.com ASP.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 ASP.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 ASP.NET MVC 2.0 Hosting :: Remote Validation with ASP.NET MVC 2

clock October 11, 2010 10:32 by author Darwin

One validation feature that we didn’t quite have time for in MVC 2’s new client-side validation support is called “remote validation”.

Remote validation means we make a call back to our web site to ensure that a given value is valid. You might want this in cases where it’s not easy (or possible) to determine whether the value is valid on the client side, but you’d still like to give the user client-side feedback about the validity of the item. The canonical example is checking to see if a desired username is taken during your site registration process.

This is an example remote validator that I modified from an example by Levi Broderick (who did the bulk of the JavaScript work for client-side validation). This example was tested on MVC 2 RC, and assumes that you’re using the DataAnnotations validation system (the default).

In order to make this work, we will need to perform a couple of one-time steps:

1. Include a JavaScript file that enables remote validation.
2.
Register a server-side adapter for remote validation.

We’ll also need to perform a couple of steps for each remote validation we want to perform:

1.
Write an action which accepts the value to be tested and returns a string, either “true” (the model is valid), “false” (the model is invalid and you want to use the default message), or any other string (the model is invalid, and the string that we return should be the error message).

2.
Put the [Remote] attribute to the model property that you want remotely validated, pointing to the action you just wrote.

The Client-Side Bits

When you want to write a client-side validator for MVC 2, you will write a function (in JavaScript) that registers the validator and performs the validation when prompted to. For remote validation, this is our example JavaScript:

Sys.Mvc.ValidatorRegistry.validators.remote = function(rule) {
    var url = rule.ValidationParameters.url;
    var parameterName = rule.ValidationParameters.parameterName;
    var message = rule.ErrorMessage;

    return function(value, context) {
        if (!value || !value.length) {
           return true;
        }

        if (context.eventName != 'blur') {
           return true;
        }

        var newUrl = ((url.indexOf('?') < 0) ? (url + '?') : (url + '&'))
                    + encodeURIComponent(parameterName) + '=' + encodeURIComponent(value);

        var completedCallback = function(executor) {
           if (executor.get_statusCode() != 200) {
              return;
           }
 
           var responseData = executor.get_responseData();
           if (responseData != 'true') {
              var newMessage = (responseData == 'false' ? message : responseData);
              context.fieldContext.addError(newMessage);
           }
        }

        var r = new Sys.Net.WebRequest();
        r.set_url(newUrl);
        r.set_httpVerb('GET');
        r.add_completed(completedCallback);
        r.invoke();
        return true;
    };
};

Put this in a .js file, and reference it in the same place where you’re already referencing MicrosoftAjax.js and MicrosoftMvcValidation.js (usually in your Site.Master file or some equivalent).

The first line sets up a new client-side validation rule named “remote”. The anonymous function sets up the rule, and returns a function which performs the validation. The function accepts the value and a context object we create for you which contains information about the actual validation you’re doing.

The first if block stops us from doing anything is there’s no value. Validators should always return success (true) when given an empty value, because it’s the “required” validator that’s responsible for denying empty values.

The second if block only runs our validation during the “blur” event (i.e., when the user tabs out of the field). The other two events are “input” (fired as the user types) and “submit” (fired when the user wants to submit the form). Neither of these are appropriate because “input” would happen too much, and “submit” is too late for a remote validation. One consequence of this is that, with this implementation, users will be allowed to submit values to the server where the remote validation might’ve failed. You could change this JS file to prevent that (stash the previous result from your “blur” event and return that during the “submit” event), but I’ll leave that as an exercise for the reader.

We append the value to the URL and submit a new GET request to the URL, and then hook the response to read the result, setting a validation error message if the response was anything other than “true”.

The Server-Side Bits

We’ll start with the RemoteAttribute class:

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Web.Routing;

[AttributeUsage(AttributeTargets.Property)]
public class RemoteAttribute : ValidationAttribute
{

    protected RemoteAttribute(string parameterName
    {
                   ParameterName = parameterName;
        RouteData = new RouteValueDictionary();
    }

    public RemoteAttribute(string action, string controller, string parameterName)
        : this(parameterName)
    {
        RouteData["controller"] = controller;
        RouteData["action"] = action;
    }

    public RemoteAttribute(string routeName, string parameterName)
        : this(parameterName)
    {
        RouteName = routeName;
    }

    public string ParameterName { get; protected set; }

    protected RouteValueDictionary RouteData { get; set; }

    protected string RouteName { get; set; }

    public virtual string GetUrl(ControllerContext controllerContext)
    {
        var pathData = RouteTable.Routes.GetVirtualPath(controllerContext.RequestContext,
                                 RouteName,
                                 RouteData);

        if (pathData == null)
           throw new InvalidOperationException("No route matched!");
        return pathData.VirtualPath;
    }

    public override bool IsValid(object value)
    {
        return true;
    }
}

This attribute derives from the DataAnnotations ValidationAttribute base class. There’s no server-side validation by default (the “return true” line in IsValid), though you could derive from this attribute to provide both server- and client-side validation. We’ll talk about this more in a bit.

There are two constructors: one where you provide action + controller + parameter name, and one where you provide route name + parameter name. ParameterName is the name of the parameter name of your action method which will receive the value to validate.

Here’s the RemoteAttributeAdapter class:

using System.Collections.Generic;
using System.Web.Mvc;  

public class RemoteAttributeAdapter : DataAnnotationsModelValidator<RemoteAttribute>
{
    public RemoteAttributeAdapter(ModelMetadata metadata,
                                  ControllerContext context,
                                  RemoteAttribute attribute) :
        base(metadata, context, attribute) { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        ModelClientValidationRule rule = new ModelClientValidationRule()
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "remote"
            };
        rule.ValidationParameters["url"] = Attribute.GetUrl(ControllerContext);
        rule.ValidationParameters["parameterName"] = Attribute.ParameterName;
        return new ModelClientValidationRule[] { rule };
    }
}

This a DataAnnotations validator adapter which enables the client-side validation support on the server side (say that 3x fast). The purpose of this class is to tell the DataAnnotations validation system what to emit into the client-side JavaScript when it finds one of these validator attributes. The values it's emitting are based on the JavaScript file we wrote above: a rule named remote, which has two parameters: url and parameterName.

You will need to register this adapter in your Global.asax file, in the Application_Start() method, by calling:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RemoteAttribute),
    typeof(RemoteAttributeAdapter)
);

Putting It All Together

Let's start with a model that uses remote validation:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

public class RemoteModel
{
    [Required]
    [DisplayName("Any Number")]
    public int AnyNumber { get; set; }

    [Required]
    [Remote("IsOdd", "Sample", "value",
            ErrorMessage = "Value for '{0}' is not odd.")]
    [DisplayName("Odd Number")]
    public int OddNumber { get; set; }
}

And the controller:

using System;
using System.Web.Mvc;

public class SampleController : Controller
{
    public string IsOdd(int value)
    {
        return ((value % 2) == 1) ? "true" : "false";
    }

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(RemoteModel model)
    {
        return View(model);
    }
}

And the view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<RemoteModel>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <p>
        Server thinks the model
        <b><%= ViewData.ModelState.IsValid ? "IS" : "IS NOT" %></b>
        valid.
    </p>
    <% using (Html.BeginForm()) { %>
        <%= Html.EditorForModel() %>
        <input type="submit" />
    <% } %>
</asp:Content>

When we fire up the page, we’ll see two editor boxes (for “Any Number” and “Odd Number”). If we click submit, we will immediately see via client-side validation that the values are not valid because they are required.

You can tell it's client-side validation, because the browser “busy” icon never spins, the page doesn't flash, and the sentinel at the top will tell you that the server still thinks your model is valid. If it looks you're still posting to the server, make sure you’ve included all 3 JavaScript files as well as called <% Html.EnableClientValidation(); %> somewhere in your view or master page.

Now type “1” into “Any Number”, and “2” into “Odd Number”, then tab away to the “Submit Query” button (don’t click it yet). The remote validation will fire and quickly you’ll see an error next to “Odd Number” which says “Value for 'Odd Number' is not odd.”.

Now take note that you can still click Submit Query, and it will still submit up to the server (as I alluded to above). More interestingly, though, is that the error went away from next to “Odd Number”. That’s because our [Remote] attribute doesn’t do any server-side validation. We could re-write it to execute the entire action and get the result, but that just seems too heavy-weight.

Instead, let’s write a new attribute which derives from RemoteAttribute:

using System;

[AttributeUsage(AttributeTargets.Property)]
public class OddNumberAttribute : RemoteAttribute
{
    public OddNumberAttribute()
        : base("IsOdd", "Sample", "value")
    {
                    ErrorMessage = "{0} must be odd.";
    }

    public override bool IsValid(object value)
    {
        if (value == null)
           return true;

        int intValue;
        if (!Int32.TryParse(value.ToString(), out intValue))
           return false;
 
        return IsOdd(intValue);
    }

    public static bool IsOdd(int value)
    {
        return ((value % 2) == 1);
    }
}

Note that we've moved our “complex logic” into the OddNumberAttribute as a static. Normally we’d probably already have isolated this logic somewhere else in our class hierarchy, but this was a convenient place for it to in the sample. The important point is that this code is reachable both from within the new attribute, as well as from the controller, because we’re going to re-write the IsOdd action on our controller to call the same logic now:

public string IsOdd(int value)
{
    return OddNumberAttribute.IsOdd(value) ? "true" : "false";
}

We update our model to use the new attribute instead of the old Remote attribute:

[Required]
[OddNumber]
[DisplayName("Odd Number")]
public int OddNumber { get; set; }

And one last change to our registration code in global.asax:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(OddNumberAttribute),
    typeof(RemoteAttributeAdapter)
);

Now back to our form, and this time when we try to submit a value with a non-odd number, the server will tell us we made a mistake. We'll get a round-trip and a flash of content, but now Odd Number will still be invalid, and our little sentinel on the top says that "Server thinks the model IS NOT valid." now.

What is so SPECIAL on ASPHostDirectory.com ASP.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 ASP.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 ASP.NET MVC Hosting :: Turn on Compile-Time View Checking

clock October 7, 2010 04:53 by author Darwin

We like the compiler to catch as many errors as possible before we start debugging or release our application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not easily unit-testable. But views are not validated at compilation, at least not when using the standard settings for ASP.NET MVC projects.

Tools like Resharper can notify you of syntax errors within your views, but you can still build the project and not get a single error. Instead, your application will crash when trying to evaluate the buggy view.

Fortunately you can easily make Visual Studio compile your views along with the rest of your code. The only downside is that your project will build a bit slower, but if this bothers you during development you can also enable this feature on a per configuration basis. For example you may want to compile your views in Release mode, but not in your Debug configuration , so you have the extra safety of compile-time view checking before releasing a new version, but you still get lightning-fast compilation times while developing.

Please proceed as follows to turn on compile time view compilation:

1. Open your .csproject or .vbproject file in a text editor of your choice. It’s just a simple xml file, which is why any editor will do fine.

2. Locate the <PropertyGroup> element that belongs to the configuration you would like to alter.

3. Within this PropertyGroup, add an additional element with “true” as its text value.

For example, this will turn on view compilation in my project’s Release configuration:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
 <MvcBuildViews>true</MvcBuildViews>
...

That’s it! The next time one of your views has compile-time errors, these will be reported when building your application.

One last thing: You need to repeat this procedure for all configurations you might create in the future if you want your views to be checked in those configurations as well. Even if you tell Visual Studio to copy settings from an existing configuration where this tag is already set to true, the MvcBuildViews tag is not copied by Visual Studio.

What is so SPECIAL on ASPHostDirectory.com ASP.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 ASP.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 MVC :: New Features in ASP.NET MVC 2.0 and Samples

clock July 17, 2010 07:35 by author Darwin

In this article, we will discuss new features ASP.NET MVC and also the examples.  ASP.NET MVC 2 builds on ASP.NET MVC 1.0. MVC 2 can be used with asp.net 3.5 SP1 and With ASP.NET 4.O. MVC 2 by default installed on your computer when you install Visual Studio 2010.

The new features of ASP.NET MVC 2:

1. Template Helper to use Lambda Expression
2. Asynchronous Controllers for parallel long running tasks and  enable to Asynchronous Operations Matter
3. Area to split large project to avoid the complexity of the large project. Right Click on your Project in the Solution Explorer, click Add and then click Area. Now you can add forum or admin in the Area
4. Strongly Typed UI Helpers to view model level error instead of all validation Errors.
5. HiddenInputAttribute Class for Templated Helpers when DisplayValue is false nothing will be happen but when DisplayValue is true then input hidden element will be rendered when  displaying model  in editor template
6. Enhancements to ModelBinders
7. Automatic HTML-Encoding
8. Enhancements to ModelBinders supports are:
- Increasing Security with HTTPS
- Avoiding the JSON Array Attack
- Short Notation for AcceptVerbs Attribute
- Overriding the HTTP Verb
- Binary Binding
- Ability to render subsections of site pages

Example

Open your Visual Studio 2010. Create New Project, window will be display on your screen, by default .Net Framework 4 is selected. Expand Visual C# and click on Web. Select ASP.NET MVC 2 Web Application
 

If you want to create Unit Test then select Yes option and give the Test Project name. By default name of the test project is the application project MvcApplication.Tests. You can change the name of project as shown in below figure.

Project is created as you see in the below Figure. Content folder includes CSS file, Script contains js Files. You have three main folders Controller, Models and Views.

Below is the Simple HomeController class.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MvcApplication.Controllers

{

    [HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            ViewData["Message"] = "This is my First MVC Web Project";

 

            return View();

        }

 

        public ActionResult About()

        {

            return View();

        }

    }

}

Here is the Code of index.aspx Page

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

    <h2><%: 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>

</asp:Content>

 

 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>

</asp:Content

Default created MVcApplication class in Global.aspx.cs file as shown in below code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace MvcApplication

{

    // Note: For instructions on enabling IIS6 or IIS7 classic mode,

    // visit http://go.microsoft.com/?LinkId=9394801

   //Author:Aamir Hasan

 

    public class MvcApplication : System.Web.HttpApplication

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

            routes.MapRoute(

                "Default", // Route name

                "{controller}/{action}/{id}", // URL with parameters

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

 // Parameter defaults

            );

        }

        protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

 

            RegisterRoutes(RouteTable.Routes);

        }

    }

}


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 MVC 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 MVC :: 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 MVC :: 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 MVC :: Validating with a Service Layer (VB)

clock June 8, 2010 06:27 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 IProductRepositor
     

    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 MVC :: How to Create a DropDownList with ASP.NET MVC

clock June 1, 2010 05:20 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 MVC :: 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!