ASP.NET 4.5 Hosting BLOG

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

ASP.NET 4.5.2 Hosting with ASPHostPortal :: How to Publish and Deploy an ASP.NET Application in IIS

clock September 16, 2014 12:08 by author Kenny

Simple Way to Publish and Deploy an ASP.NET Application in IIS

ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. While Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

In this post, we will describe you how to publish and deploy your ASP.NET application in IIS. Actually it is so simple thing, you can publish your web application to the File System and copy paste all the files to your server. After that, you can add a new website from IIS. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

You can add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?

ASP.NET 4.5.2 Hosting with :: SEO Tips for Your ASP.NET Site

clock August 23, 2014 09:42 by author Kenny

Here are 7 tips on SEO for your ASP.NET website:

A Microsoft server-side Web technology. ASP.NET takes an object-oriented programming approach to Web page execution. Every element in an ASP.NET page is treated as an object and run on the server. An ASP.NET page gets compiled into an intermediate language by a .NET Common Language Runtime-compliant compiler.

Page Titles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  • External stylesheets and not inline CSS
    • js files instead of inline JavaScript
  • HTML comments is not encouraged
  • Avoid massive line breaking
  • Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed. 

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.

ASP.NET 4.5.2 Hosting with :: Token Based Authentication using ASP.NET Web API 2, Owin, and Identity.

clock July 22, 2014 09:26 by author Kenny

In this article, we are going to explain about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. As you know that a token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

What is Token Based Authentication?

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server. An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request. After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

What is ASP.NET Web API 2, Owin, and Identity?

This article is about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. ASP.NET Identity is the reworked, flexible replacement for the old membership system that has been around since ASP.NET 2.0. ASP.NET Identity is more well designed and flexible than the old membership system and uses Owin middleware components for external logins such as Facebook, Google and Twitter.

Building the Back-End API

Step 1: Creating the Web API Project

Now create an empty solution and name it “AngularJSAuthentication” then add new ASP.NET Web application named “AngularJSAuthentication.API”, the selected template for project will be as the image below. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Step 2: Installing the needed NuGet Packages:

Now we need to install the NuGet packages which are needed to setup our Owin server and configure ASP.NET Web API to be hosted within an Owin server, so open NuGet Package Manger Console and type the below:

Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2

Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0

The  package “Microsoft.Owin.Host.SystemWeb” is used to enable our Owin server to run our API on IIS using ASP.NET request pipeline as eventually we’ll host this API on Microsoft Azure Websites which uses IIS.

Step 3: Add Owin “Startup” Class

Right click on your project then add new class named “Startup”. We’ll visit this class many times and modify it, for now it will contain the code below:
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

[assembly: OwinStartup(typeof(AngularJSAuthentication.API.Startup))]

namespace AngularJSAuthentication.API


    public class Startup


        public void Configuration(IAppBuilder app)


            HttpConfiguration config = new HttpConfiguration();






What we’ve implemented above is simple, this class will be fired once our server starts, notice the “assembly” attribute which states which class to fire on start-up. The “Configuration” method accepts parameter of type “IAppBuilder” this parameter will be supplied by the host at run-time. This “app” parameter is an interface which will be used to compose the application for our Owin server.

The “HttpConfiguration” object is used to configure API routes, so we’ll pass this object to method “Register” in “WebApiConfig” class.

Lastly, we’ll pass the “config” object to the extension method “UseWebApi” which will be responsible to wire up ASP.NET Web API to our Owin server pipeline.

Usually the class “WebApiConfig” exists with the templates we’ve selected, if it doesn’t exist then add it under the folder “App_Start”. Below is the code inside it:

    public static class WebApiConfig
       public static void Register(HttpConfiguration config)
            // Web API routes

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

           var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Step 4: Delete Global.asax Class

No need to use this class and fire up the Application_Start event after we’ve configured our “Startup” class so feel free to delete it.

Step 5: Add the ASP.NET Identity System

After we’ve configured the Web API, it is time to add the needed NuGet packages to add support for registering and validating user credentials, so open package manager console and add the below NuGet packages:

Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1

Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.0.1

The first package will add support for ASP.NET Identity Owin, and the second package will add support for using ASP.NET Identity with Entity Framework so we can save users to SQL Server database.

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “AuthContext” then paste the code snippet below:

public class AuthContext : IdentityDbContext<IdentityUser>
        public AuthContext()
            : base("AuthContext")

As you can see this class inherits from “IdentityDbContext” class, you can think about this class as special version of the traditional “DbContext” Class, it will provide all of the Entity Framework code-first mapping and DbSet properties needed to manage the identity tables in SQL Server.

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so add new class named “AuthRepository” and paste the code snippet below:

    public class AuthRepository : IDisposable
        private AuthContext _ctx;

        private UserManager<IdentityUser> _userManager;
        public AuthRepository()
            _ctx = new AuthContext();
            _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
          IdentityUser user = new IdentityUser
            {            UserName = userModel.UserName
            var result = await _userManager.CreateAsync(user, userModel.Password);
            return result;
        public async Task<IdentityUser> FindUser(string userName, string password)
        IdentityUser user = await _userManager.FindAsync(userName, password);
            return user;
        public void Dispose()

Step 7: Add our “Account” Controller

Now it is the time to add our first Web API controller which will be used to register new users, so under file “Controllers” add Empty Web API 2 Controller named “AccountController” and paste the code below:

    public class AccountController : ApiController
          private AuthRepository _repo = null;
          public AccountController()
           _repo = new AuthRepository();
        // POST api/Account/Register
        public async Task<IHttpActionResult> Register(UserModel userModel)
         if (!ModelState.IsValid)
              return BadRequest(ModelState);
            IdentityResult result = await _repo.RegisterUser(userModel);
            IHttpActionResult errorResult = GetErrorResult(result);
            if (errorResult != null)
              return errorResult;
              return Ok();
        protected override void Dispose(bool disposing)
           if (disposing)
        private IHttpActionResult GetErrorResult(IdentityResult result)
          if (result == null)
             return InternalServerError();
            if (!result.Succeeded)
              if (result.Errors != null)
                  foreach (string error in result.Errors)
                     ModelState.AddModelError("", error);
                if (ModelState.IsValid)
                // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                return BadRequest(ModelState);
            return null;

Step 8: Add Secured Orders Controller

Now we want to add another controller to serve our Orders, we’ll assume that this controller will return orders only for Authenticated users, to keep things simple we’ll return static data. So add new controller named “OrdersController” under “Controllers” folder and paste the code below:

    public class OrdersController : ApiController
        public IHttpActionResult Get()
         return Ok(Order.CreateOrders());
    #region Helpers
    public class Order
   public int OrderID
        public string CustomerName
        public string ShipperCity
        public Boolean IsShipped
        public static List<Order> CreateOrders()
         List<Order> OrderList = new List<Order>
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            return OrderList;

Step 9: Add support for OAuth Bearer Tokens Generation

Till this moment we didn’t configure our API to use OAuth authentication workflow, to do so open package manager console and install the following NuGet package:

Install-Package Microsoft.Owin.Security.OAuth -Version 2.1.0

After you install this package open file “Startup” again and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implemntation for this method as below:

public class Startup
    public void Configuration(IAppBuilder app)
                    //Rest of code is here;
        public void ConfigureOAuth(IAppBuilder app)
          OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            // Token Generation
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

Step 10: Implement the “SimpleAuthorizationServerProvider” class

Add new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
   context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (AuthRepository _repo = new AuthRepository())
   IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
                if (user == null)
                {context.SetError("invalid_grant", "The user name or password is incorrect.");
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

Step 11: Allow CORS for ASP.NET Web API

First of all we need to install the following NuGet package manger, so open package manager console and type:

Install-Package Microsoft.Owin.Cors -Version 2.1.0

Now open class “Startup” again and add the highlighted line of code (line 8) to the method “Configuration” as the below:

public void Configuration(IAppBuilder app)
            HttpConfiguration config = new HttpConfiguration();
            app.UseWebApi(config);        }

Step 12: Testing the Back-end API

Assuming that you registered the username “Taiseer” with password “SuperPass” in the step below, we’ll use the same username to generate token, so to test this out open your favorite REST client application in order to issue HTTP requests to generate token for user “Taiseer”. For me I’ll be using PostMan.

ASPHostPortal Web Hosting Announces Release of New Free 7 Days ASP.NET MVC 5.2 Hosting

clock June 6, 2014 07:48 by author Ben

Windows and ASP.NET hosting specialist,, has announced the availability of new hosting plans that are optimized for the latest update of the ASP.NET MVC  technology. The ASP.NET MVC 5.2 Release Candidate is now available to developers for immediate download. ASP.NET MVC 5.2 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. This package contains the runtime assemblies for ASP.NET MVC. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. ASP.NET MVC 5.2  brings bootstrap into the default MVC template, authentication filters, filter overrides and attribute routing.  Attribute Routing on ASP.NET MVC 5.2 now provides an extensibility point called IDirectRouteProvider, which allows full control over how attribute routes are discovered and configured. - a cheap, constant uptime, excellent customer service, quality and also reliable hosting provider in advanced Windows and ASP NET technology. hosts its servers in top class data centers that is located in United States to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from include 24×7 support and 30 days money back guarantee.

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5.2 hosting services, we hope that developers and our existing clients can try this new features. Now, you don’t need to spend a lot of money to get ASP.NET MVC 5.2 hosting.”

For more information about new ASP.NET MVC 5.2, please visit

As a leading hosting provider, offers a comprehensive range of services including domain name registrations, servers, online backup solutions and dedicated web hosting. is well placed to deliver a high quality service.

About is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.

ASP.NET MVC 5.1.2 Hosting with :: Loading a Knockoutjs Model from a ASP.NET MVC Controller Using AJAX

clock May 21, 2014 11:51 by author Kenny

Knockout.js is a javascript library that allows us to bind html elements against any data model. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM(UI) and any changes to the DOM are automatically reflected to the data model.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. The MVC model defines web applications with 3 logic layers: The business layer (Model logic),The display layer (View logic),The input control (Controller logic).

This article will demonstrate how to load a KnockoutJS view model from a C# controller using ajax in an ASP.NET MVC project. I’m just going to jump straight into the code for this sample.  To get started we need to create a new action in the controller.  For the purposes of this sample this action will return a randomly populated Person object (see the previous articles for the definition) so that we can see the content changing.  Here is the action:

public class SampleController : Controller
    public ActionResult AjaxModelLoading()
        Person model = CreateRandomModel();
        if (Request.IsAjaxRequest())
            return new JsonNetResult(model);
        return View(model);
    private static Person CreateRandomModel()
        Random random = new Random();
        string[] firstNames = { "Billy", "Kevin", "Michael", "Steve" };
        string[] lastNames = { "Jordan", "Smith", "Wild", "Walker" };
        string firstName = firstNames[random.Next(firstNames.Length)];
        string lastName = lastNames[random.Next(lastNames.Length)]; 
        return new Person
            FirstName = firstName,
            LastName = lastName,
            EmailAddress = string.Format("{0}@{1}.com", firstName, lastName),
            PhoneNumber = random.Next(int.MaxValue).ToString("D10"),
            DateOfBirth = DateTime.Today.AddYears(random.Next(-50, -10))

This action creates the Person object and then detects if the HTTP request was made using ajax.  If it was then it serializes the model as JSON and if it is a standard HTTP request it returns the view.  This is a handy technique for implementing a simple refresh of data in the view without retrieving all the HTML from the server again.

On line 9 you can see that I have not used the standard ASP.NET JSON serializer.  Instead I went with my own ActionResult which makes use of JSON.NET to give myself more control over the generated JSON.  For reference the code for my JsonNetResult class is below:
public class JsonNetResult : ActionResult
    private const string ContentType = "application/json"; 
    private readonly object data;
    private readonly Formatting formatting;
    private readonly JsonSerializerSettings serializerSettings; 
    public JsonNetResult(object data)
    { = data;
        formatting = Formatting.None;
        serializerSettings = new JsonSerializerSettings
            ContractResolver = new CamelCasePropertyNamesContractResolver()
    public override void ExecuteResult(ControllerContext context)
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = ContentType;
        if (data != null)
            JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = formatting };
            JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
            serializer.Serialize(writer, data);
    public object Data
        get { return data; }

Next we need to create the KnockoutJS view model to bind to the view.
var AjaxModelLoading = function(url) {
    var self = this;
    self.isLoaded = ko.observable(false);
    self.isLoading = ko.observable(false); 
    self.getRandomModel = function () {
        // Setting a timeout so the loading text is visible in the sample
        setTimeout(function() {
            $.ajax(url, {
                type: "GET",
                cache: false,
            }).done(function(data) {
                ko.mapping.fromJS(data, {}, self);
        }, 1000);

This view model defines a function which will be used to handle a click event from the view in order to refresh the data. It also does some basic state management to determine if the content has been loaded or is in the process of loading.  I have put in a short delay between the click in the view and executing the ajax request in order to make the loading state management more apparent for the sample.

Lastly we need to create the view.
@model Quickstart.Web.Models.Person 
@section scripts
    <script type="text/javascript" src="/Scripts/ViewModels/AjaxModelLoading.js"></script>
    <script type="text/javascript">
        var viewModel = new AjaxModelLoading("@Url.Action("AjaxModelLoading")");
<h2>Ajax Model Loading Sample</h2>

<div data-bind="if: isLoading()">
<div data-bind="if: isLoaded()">
        <label>First Name:</label>
        <input type="text" data-bind="value: firstName"/>
        <label>Last Name:</label>
        <input type="text" data-bind="value: lastName"/>

        <label>Email Address:</label>
        <input type="text" data-bind="value: emailAddress"/>
        <label>Phone Number:</label>
        <input type="text" data-bind="value: phoneNumber"/>
        <label>Date of Birth:</label>
        <input type="text" data-bind="value: dateOfBirth"/>
<a href="#" data-bind="click: getRandomModel">Get random person</a>

ASP.NET MVC 5 Hosting - with :: How to Rendering ASP.NET MVC 1.0, 2.0 RC, 3 and 4 Razor Views to String

clock March 14, 2014 07:44 by author Diego

The ASP.NET MVC Razor implementation is closely tied to ASP.NET and MVC and the View template (WebViewPage class) includes a few MVC-specific features as well as back references to the controller. In other words MVC Razor is designed with MVC in mind. With Razor, you can create a custom Razor Engine that can be used in any .NET environment. Razor is the best view engine available for MVC as its much cleaner and easy to write and read. This view engine is compatible with unit testing frameworks. In this article, I will demonstrate how you can render ASP.NET MVC Razor Views in ASP.Net MVC 1.0, 2.0 RC, 3 and 4 .
Basically, all you do is create a fake HttpContext for the view to render itself.  This is an extensions method of the HtmlHelper that processes a partial view through the default MVC view engine and then renders it to the response stream.

Thisworks on ASP.NET MVC 1.0 (changing Headers on the original HttpResponse doesn't throwthe "Server cannot set content type after HTTP headers have been sent"exception).
/// <summary>Renders a view to string.</summary>
public static string RenderViewToString(this Controller controller, string viewName, object viewData) {

Create memory writer.

var sb = new StringBuilder();
var memWriter = new StringWriter(sb);

Create fake http context to render the view.

    var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(
        new HttpContextWrapper(fakeContext),
    var oldContext = HttpContext.Current;
    HttpContext.Current = fakeContext;
  Use HtmlHelper to render partial view to fake context.
    var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), new ViewDataDictionary(), new TempDataDictionary()),
        new ViewPage());
    html.RenderPartial(viewName, viewData);
Restore context.
    HttpContext.Current = oldContext;  
    //Flush memory and return output
    return sb.ToString();}
Fake IView implementation used to instantiate an HtmlHelper.
public class FakeView : IView {
    #region IView Members
    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        throw new NotImplementedException();
    }    #endregion

In ASP.NET MVC 2.0 RC, the code changes a bit because we have to pass in the StringWriter used to write the view into the ViewContext:
Use HtmlHelper to render partial view to fake context.

var html = new HtmlHelper(
    new ViewContext(fakeControllerContext, new FakeView(),
        new ViewDataDictionary(), new TempDataDictionary(), memWriter),
    new ViewPage());
html.RenderPartial(viewName, viewData);

In MVC 3 you can used this code :
public static string RazorRender(Controller context, string DefaultAction)
string Cache = string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.TextWriter tw = new System.IO.StringWriter(sb);
RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);
Cache = sb.ToString();
return Cache;
public static string RenderRazorViewToString(string viewName, object model)
ViewData.Model = model;
using (var sw = new StringWriter())
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
public static class HtmlHelperExtensions
public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
if (result.View != null)
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
using (HtmlTextWriter output = new HtmlTextWriter(sw))
ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
return sb.ToString();

return String.Empty;

This code worked in MVC 4 :
public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();

I hope you will enjoy this Article, and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates with ASPHostPortal

ASP.NET MVC 5 Hosting - with :: What are Differences ViewBag, ViewData and TempData in Asp.Net MVC 5 ?

clock March 12, 2014 05:49 by author Diego

In Asp.Net MVC 5 (Model-View-Controller) there are three options ViewBag, ViewData, and TempData to pass small amount of data from controller to view. In this article i am going to explain what is ViewBag, ViewData and TempData and their use in Asp.Net MVC 5.

A. ViewData & ViewBag objects.
is a dictionary object that you put data into, which then becomes available to the view.It is an in-built dictionary object that is derived from ViewDataDictionary class that can be accessed and set with string type key values. It is a used to pass data from Controller to View. ViewData's value become null if redirection occur because its life lies only during current request.

Key points to remember about ViewData.

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewData requires typecasting for complex data type and it is recommended to check for null values to avoid error.
  • ViewData is used to pass small amount of data from controller to view, so it helps to maintain data when moving from controller to view.
  • ViewData has short life i.e.  Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewData is to provide a way to transfer/pass data from controllers and views.
  • ViewData is faster than ViewBag.

ViewData Example.
In View:


ViewBag is dynamic object, meaning we can add properties to it in the controller, and read them later in the view. Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewBag is to provide a way to transfer/pass data from controllers and views.

ViewBag Example:
In View:


Similarities between ViewBag & ViewData :
Both the ViewData and ViewBag objects are great for accessing extra data (i.e., outside the data model), between the controller and view. Since views already expect a specific object as their model, this type of data access to extra data, MVC implements it as a property of both views and controllers, making usage and access to these objects easy. Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

B. TempData Object.The problem with the ViewData and ViewBag for transferring data from controller to view is that the data is only alive for current request. The data is lost if a redirection takes place i.e. if one Action redirects to another action. But when we need to persist the data between actions/redirection then MVC offers another dictionary object called TempData for that purpose. It is derived from TempDataDictionary and created on top of session. It will live till the redirected view is fully loaded. “TempData”  Helps to maintain data when you move from one controller to other controller or from one action to other action.The benefit is that if you have a chain of multiple redirections it won’t cause TempData to be emptied the values will still be there until you actually use them, then they clear up after themselves automatically.

When to use TempData in ASP.NET MVC ?
Example condition :

I came across this problem where I had a basic list of items and for each if these items I wanted to add a delete action on my controller. I wanted to add some error checking around the delete action so if someone attempted to modify the URL and enter a incorrect parameter into my controller, I wanted to redirect back to the previous controller and notify the user of this mistake. Take this example. I have a Product Controller and the Index Action and View lists all of the products. I have a delete action on the Product Controller which checks if the productId parameter is valid and then removes the product and redirects to the Index action using the RedirectToAction method.

The solution :
When validating the productId, if its NOT valid simply add a new key/value to the TempData object and call the RedirectToAction method. TempData stores data for short periods of time for the current and next HTTP request. In your index view, you can check to see if your key/value pair exists and display a error message. If you refresh the page, you will notice the data from the TempData will be gone. Remember to use RedirectToAction where possible as this is more friendly with Unit Testing rather than using the HttpResponse redirect method.

I hope you have got what is ViewBag, ViewData and TempData in Asp.Net MVC and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates.

ASP.NET MVC 5.1.1 Hosting with :: Difference between ASP.NET Web Forms and ASP.NET MVC

clock March 5, 2014 09:53 by author Kenny

Now I wiil expose the main difference between ASP.NET Web Form and ASP.NET MVC.
ASP.NET Web Forms is a part of the ASP.NET web application framework. Web Forms are pages that your users request through their browser and that form the user interface (UI) that give your web applications their look and feel. These pages are written using a combination of HTML, server controls, and server code. When users request a page, it is compiled and executed on the server, and then it generates the HTML markup that the browser can render. Using Visual Studio, you can create ASP.NET Web Forms using a powerful IDE. For example, this lets you drag and drop server controls to lay out your Web Forms page. You can then easily set properties, methods, and events for controls or for the page in order to define the page's behavior, look and feel, and so on. To write server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. A model represents the state of a particular aspect of the application. A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view. A view accepts necessary information from the controller and renders a user interface to display that information.
ASP.NET developers have two options when building new Web projects: ASP.NET Web Forms or ASP.NET MVC framework.
There are the different
between ASP.NET Web Form and ASP.NET MVC:

ASP.Net Hosting – :: Adding Email Confirmation to ASP.NET Identity in MVC 5

clock February 19, 2014 09:14 by author Diego

One of the mainline features about ASP.NET Identity is to make it easy to Adding Email Confirmation. This process will send an email to the user with a link they can click on to confirm their registration and log in to the system. Prior to confirmation they will not be able to log in.


This post shows how you can adding email confirmation to ASP.NET Identity in MVC 5.

First I started by creating a new MVC 5 application.  You no longer select whether you want an Internet or Intranet application, you just select the MVC template and select the authentication type you want to use. For an Internet type application you select Individual User Accounts.  Once your web application is created open IdentityModels.cs in the Models directory.  You will see a class called ApplicationUser which is analogues to the UserProfile in SimpleMembership.  It is an empty class that inherits from IdentityUser which has these properties.

You must to modify the user information to store a the confirmation token and a flag indicating whether confirmation was completed or not.

Now let’s implement the method in the AccountMembershipService class:


Here, we’re setting the confirmationGuid to user. This is the GUID stored in the database that uniquely identifies the user. We then set the verifyUrl to the Verify action on the Account controller – passing the confirmationGuid as the ID parameter. The redirect to the RegisterStepTwo action just displays a view to the user that tells them to look for the email to complete the registration process.

Once the user gets the email they click on the link that will take us back to the controller action RegisterConfirmation. With that configured, when the user clicks the register button, they’ll be sent an email with the confirmation link it, and they’ll be redirected to the confirmation page. If we find a user we set IsConfirmed to true and return true from the method; otherwise we return false. If the user is confirmed they will be able to log in.

That is all there is to setting up email confirmation using ASP.NET Identity in MVC 5.


ASP.NET MVC 5.1 Hosting :: Proudly Launches ASP.NET MVC 5.1 Hosting

clock January 28, 2014 07:48 by author Ben officially launches ASP.NET MVC 5.1  hosting at affordable prices. Instant Setup, Fast and Friendly Support!, a leading innovator in Windows Hosting, announces the launch of ASP.NET MVC 5.1 Hosting. The ASP.NET MVC 5.1 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET.

ASP.NET MVC 5.1 contains a number of advances over previous versions, including the ability to define routes using C# attributes and the ability to override filters,Enum support in Views, Support for current Context in Unobtrusive Ajax, Filter Overrides and etc. The user experience of building MVC applications has also been substantially improved.

The company believes in providing top-notch service at affordable price. They offer ASP.NET MVC 5.1 hosting with the following features such as Unlimited Domain, Unlimited Subdomain, 5 GB Disk Space, 2 SQL Database and Unlimited Email Account.
“Our customers have been asking us about MVC 5.1 and we are happy to deliver a hosting platform that supports all the latest in the Microsoft Web Stack.” said said Dean Thomas, Manager at  "And it proves that we remain at the forefront in Microsoft technology".

Where to look for the best ASP.NET MVC 5.1 hosting service? How to know more about the different types of hosting services? Read more about it on

About is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.

Cheap ASP.NET 4.5 Hosting

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

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

Author Link


Corporate Address (Location)

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

Tag cloud

Sign in