ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

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

ASP.NET Hosting - ASPHostPortal.com :: ASP.NET MVC vs ASP.NET - Which is better?

clock June 3, 2016 22:54 by author Dan

When developers start to build new web projects they face two options- either using ASP.NET MVC framework or ASP.NET web forms. These days, more and more companies are however choosing the MVC based framework to revise their existing sites significantly or to develop new ones. The framework has a multitude of benefits as well as technical goodies which have made it the darling among the developers.

MVC, short for Model-View-Controller is an architectural pattern that helps in division of an application into three basic components- the controller, the model and the view. This framework is a great alternative to the web forms pattern when creating applications since it is highly testable as well as lightweight presentation framework. It comes integrated with all current .NET features like authentication based on membership as well as master pages. Most developers are quite familiar with the pattern. Here is a low-down on the advantages that the MVC based framework offers over the web forms.

Separating application tasks or concerns- A huge advantage in the framework is that it clearly separates Business Logic, Data, Model, UI, test-driven development and testability. Core contracts of the framework are interface-based for which mock objects may be used for the testing. These mock objects are simulated objects imitating the behaviours of application's actual objects. The application can be unit-tested without making the controllers run, making the testing more flexible as well as fast. Any framework may be used for the testing.

Clientcaching

Silverlight makes this available to us. When we integrate Silverlight full advantage may be taken of the feature. This leads to faster application loading; in fact some part of processing may be done through web browsers, this makes the execution of client site as well as the server side a lot faster. You can even integrate JQuery and MVC so that the code written runs in browser, taking away a huge load away from the server.

HTML size

In ASP.NET there is a huge problem in the HTML size of view state as well as controls. All data rendered is stored by view state with the final result being the final HTML getting too large. For those on slow internet connections, the loading time will be slow as well as delayed. The current framework takes care of that problem since the view state concept is absent here.

Supporting ASP.NET routing

This URL-mapping component is very powerful, letting you build applications with searchable and comprehensible URLs. Through this there is no need for URLs to include extensions of file-names since the design supports patterns of URL naming and these work good enough for SEO or search engine optimization as well as REST or representational state transfer addressing.

Pluggable as well as extensible framework

The design of MVC's components makes them easily customizable or replaceable. Individual view engine, action-method parameter serialization, URL routing policy as well as other components can be plugged in. The use of DI or Dependency Injection and IOC or Inversion of Control container models is also supported. With DI you can inject objects into classes and it does not rely on class for creation of object itself. The testing is made easier by the condition imposed that when an object is required by another object then another object should be sourced from an external source like configuration file.

The biggest advantage of ASP.NET MVC platform is that it contains all the features as well as advantages of .NET since the basis is the same for both. However, some disadvantages are that understanding codes during the process of customization may not be an easy process. Another problem is the cost- the start-up costs are much higher in the MVC platform when compared to the web form based one. But looking at the benefits that are enjoyed by the developers and the end result, this is but a small price to pay for. You can get in touch with a asp.net application development company who can help you develop web apps that are stable, scalable and secure.

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.Net Hosting - ASPHostPortal.com :: Solving Time View Errors in ASP.NET MVC

clock June 4, 2015 06:40 by author Dan

One of the best things about using a compiled language over a scripting language is that you get compile-time checks that prevent run-time errors later. ASP.NET MVC uses a hybrid approach by default. Views are compiled at run-time, but controllers, models, and other classes are pre-compiled. MVC also allows you to create strongly-typed views, but since those views aren’t compiled until run-time, you don’t always get warned about changes to your models (like property name changes) or other errors in your view until it’s running.

There’s a simple way to change this, though, by setting the views to build at compile time. Unfortunately this setting isn’t exposed in the Project Properties page in Visual Studio, but can still set it up manually. Here’s how:

    >> Right-click on your project file in Visual Studio’s Solution Explorer and choose Unload Project.
    >> Right-click the project file again and choose Edit YourProject.csproj.
    >> Look for a node called <MvcBuildViews> in the first <PropertyGroup> node (the one without any other attributes). If it’s not there, add it.
    >> Add or update the value inside the <MvcBuildViews> node to true. When you’re done it should look like this:

    <MvcBuildViews>true</MvcBuildViews>

    >> Save the project file changes.
    >> Right-click the project file in Solution Explorer one last time and select Reload Project.

Your views will now be built at compile -time and you will get syntax errors from any mistakes in your Razor syntax or breaking changes to your model, and you’ll get them long before your code makes it in front of users.

Keep in mind that, though, if you like to edit your .cshtml files while you’re running the debugger, these changes will no longer show up in the browser until you recompile the application again. I guess you can’t have it all!

Best ASP.NET Hosting Recommendation

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



ASP.NET Hosting - ASPHostPortal.com :: Solving Cannot Attach The File '.mdf' as Database in MVC

clock May 28, 2015 06:44 by author Dan

While doing database update using code-first migrations in ASP.Net MVC, came across the strange exception and details are as follows,

Issue back ground details,
1. Manually deleted auto created ".mdf" file from App_Data folder using Visual Studio.
2. Executed update-database in package manager console. Then got the below exception,

System.Data.SqlClient.SqlException (0x80131904): Cannot attach the file 'E:\Backup\Practice\MVC4\DotNetExamples\DotNetExamples\App_Data\DotnetExamples.mdf' as database 'DotnetExamples'.

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)

at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)

at System.Data.SqlClient.SqlConnection.Open()

at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)

at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)

at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)

at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)

at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)

at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)

at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)

at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)

at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)

at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()

at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()

ClientConnectionId:7c44a645-a831-418e-b8e6-88232006e97a

 
No clue about this, how to resolve and after spending lot of time searching on web, came across the following solution. Keeping this for my future reference and it might help for others for same type of problem,

Solution:

If you delete the DB file, it still stays registered with SqlLocalDB. Sometimes it fixes it by deleting DB. We can do this from the command line.

Open the "Developer Command Propmpt for VisualStudio" under your "Start/Programs menu->All Programs->Visual Studio 2012->Visual Studio Tools"

    Run the following commands:

    sqllocaldb.exe stop v11.0

    sqllocaldb.exe delete v11.0


Now execute "update-database" command from package manager console and it will create database for you without any obstacles.

Best ASP.NET Hosting Recommendation

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



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Create Various Charts for ASP.NET MVC Applications

clock February 3, 2015 06:02 by author Mark

How to Create Various Charts like Line, Column, Area and Pie for ASP.NET MVC Applications.

In this article we will see how to create various charts like Line, Column, Area and Pie for ASP.NET MVC applications. In this article we will use a third party chart control so you will also learn how to use the third party control in ASP.Net MVC application. In my last two articles i.e. Display Graph in ASP.NET MVC and Charts for Asp.Net Application you saw how to prepare the chart/graph for ASP.Net and ASP.Net MVC. Charts for Asp.Net Application here I'm using some third party chart control to prepare the chart for ASP.Net. In this article also I'm using the same chart control with a MVC application. In a normal ASP.Net application all of you are aware of using third party controls in your application but in MVC it is slightly different.
In this article we will create four different kinds of charts as mentioned below.

  • Line Chart
  • Column Chart
  • Pie Chart
  • Area Chart

Step 1 :  For creating these various charts in our application we use the WebChart.dll file so simply download the attachment and add the reference to your project.
Step 2 : Add the controller Home in your project and write the different methods for calling different charts like below.

public ActionResult Index()
       {
             return View();
        }
        public ActionResult Line()
        {
            return View();
        }
        public ActionResult Area()
        {
            return View();
        }
        public ActionResult Pie()
        {
            return View();
        }
        public ActionResult Column()
        {
            return View();
        }

Step 3 : Now add the View for index and keep the Action links for calling different methods in Home controller like below.

<%=Html.ActionLink("Line Chart","Line") %>
<%=Html.ActionLink("Area Chart","Area") %>
<%=Html.ActionLink("Pie Chart","Pie") %>
<%=Html.ActionLink("Column Chart","Column") %>

Step 4 : First, on the top of the page, register one tag prefix to refer to the WebChart.dll and import the namespaces i.e. WebChart and System.Drawing like below.

<%@ Register TagPrefix="Web" Namespace="WebChart" Assembly="WebChart" %>
<%@ Import Namespace="WebChart"%>
<%@ Import Namespace="System.Drawing"%>

Step 5 : In the head section of your view write the following script.

<script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {              
                AreaChart chart = new AreaChart();
                chart.Fill.Color = Color.FromArgb(50, Color.SteelBlue);
                chart.Line.Color = Color.SteelBlue;
                chart.Line.Width = 2;
                chart.Legend = "The Legend What You Want";
                //can pull the values from database             
                chart.Data.Add(new ChartPoint("Vulpes", (float)System.Convert.ToSingle(350)));
                chart.Data.Add(new ChartPoint("SP Nayak", (float)System.Convert.ToSingle(185)));
                chart.Data.Add(new ChartPoint("Krishna", (float)System.Convert.ToSingle(55)));
                chart.Data.Add(new ChartPoint("Datta Kharad", (float)System.Convert.ToSingle(40)));
                chart.Data.Add(new ChartPoint("Jignesh Trivedi", (float)System.Convert.ToSingle(30)));
                chart.Data.Add(new ChartPoint("Prabhu Raja", (float)System.Convert.ToSingle(25)));
                ConfigureColors();
                ChartControl1.Charts.Add(chart);
                ChartControl1.RedrawChart();
            }
        }
        private void ConfigureColors()
        {
            ChartControl1.Background.Color = Color.FromArgb(75, Color.SteelBlue);
            ChartControl1.Background.Type = InteriorType.LinearGradient;
            ChartControl1.Background.ForeColor = Color.SteelBlue;
            ChartControl1.Background.EndPoint = new Point(500, 350);
            ChartControl1.Legend.Position = LegendPosition.Bottom;
            ChartControl1.Legend.Width = 40;
             ChartControl1.YAxisFont.ForeColor = Color.SteelBlue;
           ChartControl1.XAxisFont.ForeColor = Color.SteelBlue;
             ChartControl1.ChartTitle.Text = "C-Sharpcorner Current Months Runner Up";
            ChartControl1.ChartTitle.ForeColor = Color.White;
             ChartControl1.Border.Color = Color.SteelBlue;
            ChartControl1.BorderStyle = BorderStyle.Ridge;
        }
    </script>

In the above code we have populated the chart control by adding chart points. You can add your own chart points. This Webchart.dll provides the different types of charts we discussed above so according to your view make a change in the first line under page load by creating different classes instance of chart type e.g.:

For Area Chart use

AreaChart chart = new AreaChart();

For Line Chart use

LineChart chart = new LineChart();

In the above code you only have to make these changes for creating your own choice chart also you can configure the colors as you need and you can create the points i.e. chart point per your requirement.

Step 6 : Add four views with each chart type by replacing the classes of WebChart. Now run your application and see the results.

Conclusion

It is quite simple to create various types of charts for our ASP.Net MVC applications.

TOP No#1 Recommended ASP.NET MVC Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Use Areas in ASP.NET MVC

clock January 29, 2015 05:57 by author Mark

Today i will explains about how to use areas in ASP.NET MVC. When we create a new MVC project then Model, View and Controller folders are created automatically.
This structure is common for simple applications, but when your application grows and becomes complex then the single Model, View and Controller can become complicated. So we can maintain a complex MVC application using areas. Using areas, we can write more maintainable code for an application cleanly separated by the modules.

Step by Step

  • So first create a new MVC empty project.
  • Then right-click on Solution Explorer and click on add and select area.

  • Provide a name.

  • Now add a second Employee area. In your Solution Explorer show your Model, View and Controller in a different student and employee area.

  • Now add a Home Controller and in the Index action add an Index View for both the student and employee area.
  • Now run the project. (Ctrl+F5).
  • For the Teacher area the follwing is the URL localhost/Teachers/Home/Index.
  • Here Teachers is the area name, Home is the controller and Index is the Action name.

  • For the Teacher area the follwing is the URL localhost/Students/Home/Index.
  • Here Students is the area name, Home is the controller and Index is the Action name.

TOP No#1 Recommended ASP.NET MVC Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET MVC Hosting - ASPHostPortal.com :: Conditional Validation Utilize ValidationAttribute

clock January 21, 2015 05:57 by author Ben

In ASP.NET MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required, MaxLength, MinLength, etc.

Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females.

Assume our registration form will contains three fields, name, sex and age, and its model will be as follows

public class RegisterationModel
{
    [Required(ErrorMessage = "*")]
    public String Name { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "Gender")]
    public Sex Sex { get; set; }

    [RequiredIf("Sex", Sex.Male, "enter your age")]
    public Int32? Age { get; set; }
}
public enum Sex
{
    Female = 1,
    Male = 2
}

Note we decorated the Age property with RequiredIf attribute, that we will create and it inherits ValidationAttribute class and override IsValid method.

The RequiredIf attribute accepts three pramaters in its constructor, first parameter is the name of the property will affect the validation (Sex property), second parameter is the value of that property that make the Age is required(Male), and third parameter is the error message that will be displayed if the validation failed.

public class RequiredIfAttribute : ValidationAttribute
{
    private String PropertyName { get; set; }
    private String ErrorMessage { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
    {
        this.PropertyName = propertyName;
        this.DesiredValue = desiredvalue;
        this.ErrorMessage = errormessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

In the IsValid method we get the current instance of RegisterationModel class using ValidationContext object and get the value of the Sex property then compare it with the desire value(Male) which make the Age is required. If the current value of Sex property equal the desired value then IsValid will return new ValidationResult object with the supplied error message.

Unfortunately this technique is working in server side only.


Recommended ASP.NET MVC 6 Hosting


ASPHostPortal.com
ASPHostPortal.com
is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




ASP.NET MVC Hosting - ASPHostPortal :: Describes Attribute Based Routing in ASP.NET MVC 5

clock January 20, 2015 05:19 by author Mark

This article will explains about describes Attribute Based Routing in ASP.NET MVC 5. Today we will have a look at one of the new features introduced in ASP.NET MVC 5, attribute based routing.

Pre-Context

We all know that ASP.NET MVC is a great platform that allows us to create and manage web applications in a much simpler manner compared to form-based web applications. There are a few things in MVC based web applications that works a little differently than standard web applications, one of them is routing.
Until now, there has been a routing table that you can define either in the Global.asax or in the RouteConfig.cs and all incoming requests would look it up to decide the rendering of a target view.
Here is the code that you might have seen previously to have note-variable routes in MVC 4 in the following example of the Route collection object.  

                         routes.MapRoute(  
                name: "Default",  
                url: "{controller}/{action}/{id}",  
                defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
                ); 

The big question: what is the need for this new routing methodology?
And the answer is: there was nothing really wrong with the previous approach of routing and in fact you can still use it in MVC 5 or use this new routing method in conjunction with the old one.
Here are a few advantages of attribute based routing:  

  • Helps developer in the debugging / troubleshooting mode by providing information about routes.
  • Reduces the chances for errors, if a route is modified incorrectly in RouteConfig.cs then it may affect the entire application's routing.
  • May decouple controller and action names from route entirely.
  • Easy to map two routes pointing to the same action.

All right, enough of talking. Let's see exactly how we can configure it and see it working.
First, we will need to enable attribute based routing on our MVC web application that can be done by only one line. All you need to do is put this line in the RegisterRoutes Method of the application.

    public static void RegisterRoutes(RouteCollection routes)  
    {  
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");         
        tes.MapMvcAttributeRoutes(); //Enables Attribute Based Routing   
        routes.MapRoute(  
            name: "Default",  
            url: "{controller}/{action}/{id}",  
            defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
        );                    
    } 

Now, here is how you can use the attribute based routing on a specific action method.

[Route("products/{id?}")]  
          public ActionResult Details(string id)   
          {  
              if (string.IsNullOrEmpty(id))   
              {  
                  return View("List", GetProductList());  
              }                   
              return View("Details", GetProductDetails());  
          }  

As shown in the method above, the Route is defined on a Details action method that lets users access the product details page either by of these paths:  
    /Product/Details/Id or /products/id
You might have observed the question mark in the route above, all it indicates is that the id is an optional parameter of the route and hence the action method logic checks if the id is null. It will show you the product listing page.

Route Prefixes

Route Prefixes are nothing but the prefix for any route that we want to apply, all we need to do is to define the route prefix on a controller so that all the action methods inside it can follow the prefix.
For example:   

         [RoutePrefix("products")]  
          public class ProductController : Controller  
          {  
              //This will be translated to /products          
             [Route]  
              public ActionResult List()  
              {  
                  return View();  
              }          
              //This will be translated to /products/2          
              [Route("{id?}")]  
              public ActionResult Details(string id)   
              {  
                  if (string.IsNullOrEmpty(id))   
                  {  
                     return View("List");  
                  }                       
                  return View("Details");  
              }  
      }

Route Constraints

Route constraints are nothing but a set of rules that you can define on your routing model / parameters that users need to follow when accessing the defined routes.
The way to define a constraint is by using the ":" character, let's have a look at the example below.
For example:

   //route gets called as /products/productname  
        [Route("products/{id:alpha}")]  
            public ActionResult GetProduct(string name)  
            {  
                return View();  
            }         
    //route gets called as /products/2  
            [Route("products/{id:int}")]  
            public ActionResult GetProduct(int id)  
            {  
                return View();  
            } 

Now you might have observed in the example above that though the method name is the same the route's parameter has some constraint on it. In other words the first method will be called if the route is accessed with a string as parameter and the second method will be called if the route is accessed with an integer in the route parameter.
You can also define your custom route constraints using an IRouteConstraint interface.

Route Areas

A Route area is nothing but the way to specify the area in a route, basically just to let the route know that the controller belongs to some area.

[RouteArea("business")]  
      [RoutePrefix("products")]  
      public class ProductController : Controller  
      {  
          //This will be translated to /business/products/list      
          [Route]  
          public ActionResult List()  
          {  
              return View();  
          }  
  }

TOP No#1 Recommended ASP.NET MVC 5 Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.

 

 



ASP.NET MVC Hosting - ASPHostPortal.com :: Donut Caching with ASP.NET MVC 6

clock January 14, 2015 06:03 by author Ben

I'm working on a new personal project during my free time and I chose to develop it with ASP.NET MVC 6 (hosted on ASPHostPortal of course...) to test the new features of this version. In this project, I need to display "Logged in as xxxx " (if the user is logged...) in the header of the page. This is a simple scenario to implement but caching could complicate the development of my web app...



My header is in my layout and is used everywhere but I would like to place an OutputCacheAttribute on some actions (the home page, etc.). If I put the attribute on an action, all of my users will see an header with "logged in as xxxx" of the first incoming query!

The solution to this problem is named "Donut Caching": you send a cached page from the server with a "fresh" portion which is not in cache (the donut's hole).
Concretely, the server does not generate the requested page (query the DB, etc.): it just needs to take the cached version and replace a specific part.

Luckily, you do not need to develop your own custom OutputCacheAttribute because there is already a very good package (There's An App A Pack For That... thanks NuGet!): MvcDonutCaching for ASP.NET MVC 3 and later...

To install the package, you can search through NuGet or directly type the following command in the "Package Manager Console":

install-package MvcDonutCaching

The use of this package is very simple... They have created several extension methods for HtmlHelper with the usual parameters plus another boolean parameter: excludeFromParentCache. I just have to call my partial view (with the "connected has xxxx"...) like that:

@Html.Action("LoginHeader", "Account", new { lang }, true)\

The last parameter of Html.Action is set to true: this partial view will be excluded from the parent cache (if there is a cache on the action...). (do not pay attention to new { lang }, it's a route's value) To make it work, you must not use the OutputCacheAttribute but the DonutOutputCacheAttribute:

[DonutOutputCache(Duration = 60, VaryByParam = "lang")]
     public ActionResult Index(string lang)
     {
         ...
     
         return View();
     }

And that's it! The first request will be cached during 60 seconds but the LoginHeader partial view will be generated every time.

(note: of course, the donut caching only works on the server side...)

Best Hosting for Your ASP.NET MVC Hosting

Following reviewed for Best ASP.NET hosting companies that help with ASP.NET MVC, ASPHostPortal is Best ASP.NET Hosting Recommendation for ASP.NET MVC. They give 99,99% uptime assured, as well as 30 Days Money back assured, superb customer service, and many more.



ASP.NET MVC Hosting - ASPHostPortal.com :: Making Your Existing ASP.NET MVC Web Site Mobile Friendly

clock September 26, 2013 05:58 by author Ben

This article will show you the basic mobile features of ASP.NET MVC 4.0. We will make the following changes using CSS and ASP.NET to an existing web site to make it more user-friendly on mobile devices: 

  • Content will fit the small screen 
  • One-direction scrolling either horizontally or vertically but not both 
  • Clean and efficient design 
  • An option to visit the desktop site 


The following is a collage of the various desktop views for the Contact controller.

Responsive Design and Mobile Views

As we saw above, the application uses the default ASP.NET MVC Template. This template uses responsive design techniques using the viewport meta-tag to pick up appropriate CSS styles. The view-port is specified in _Layout.cshtml. It essentially sets the device-width reported by the browser as the width of the content frame.



Using the CSS Media queries in the Site.css, the browser switches UI based on the width of the device


As we can see above, the Media query defines a set of CSS style for width up to 850 pixels. Any width lesser than 850px is considered a mobile view in the default CSS.

With the Responsive Design in place, if we look at the site on a Mobile device, this is how it looks

Except for the Index page, the rest are usable but they look out of place or retro-fitted.

Adding First Class Mobile Support using jQuery Mobile

Now that we’ve seen the limitations for Responsive CSS, let’s explore dedicated Mobile Views and the special MVC ViewSwitcher.

- From Package Manager Console, install the jQuery.Mobile.Mvc package as follows

PM> install-package jQuery.Mobile.MVC

- This installs a host of things including jQuery Mobile UI Themes, a new Configuration file called BundleMobileConfig, a new Controller called ViewSwitcherController, an empty Context file called AddingMobileSupportToMVCContext, _Layout.Mobile.cshtml and _ViewSwitcher.cshtml.


The _ViewSwitcher.cshtml checks if the browser is Mobile browser or not and generates an appropriate link to switch views. ViewSwitcherController uses the value passed to it when user clicks on the View Switcher link and switches to the appropriate view. We’ll see what we mean by Appropriate View in the next section.

_Layout.Mobile.cshtml

As we saw, this partial view was added when we added the jQuery Mobile package. The .Mobile convention is baked into MVC and when the GetOverriddenBrowser().IsMobileDevice returns true, MVC goes and checks for .Mobile.cshtml files and starts rendering them as available. So if you only have the _Layout.Mobile.cshtml and no Index.Mobile.cshtml in your view folder, MVC will fall back on the standard Index.cshtml view while using the _Layout.Mobile.cshtml as the default layout.

This is a VERY powerful mechanism we’ve got here.

It’s worth noting .Mobile is not hardcoded, rather the default. We can have .WP7, .WP8, .Iphone, .Android or any such specially targeted views as we deem required.

With the ViewSwitcher and _Layout.Mobile.cshtml in place, now if we run the application, the Home page and Edit page look as follows. Note only the underlying _Layout page has changed to _Layout.Mobile. No new views have been introduced.

 



Cheap ASP.NET 4.5 Hosting

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

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


Author Link


 

Corporate Address (Location)

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

Tag cloud

Sign in