ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

ASP.NET MVC 3 Hosting :: WebGrid in ASP.Net MVC3 Razor with Entity Framework

clock November 17, 2011 15:06 by author darwin

Hello, today I will talk about WebGrid in ASP.NET MVC 3 Razor. Yesterday, I talked much about ASP.NET MVC 4 and now back to ASP.NET MVC 3 again. J

OK, let’s start it, don’t waste our time.

1. Create a new ASP.Net MVC 3 application with an empty web application. While creating the project check the radio button "UnitTest".

2. Now under the "Model" folder create two classes.



3. Now in the Blog Class copy the following code:

public class Blog
    {
       
        [Key]      
        public int BlogId { get; set; }

        [Required(ErrorMessage = "BlogName is required")]
        public string BlogName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(120, ErrorMessage = "Description Name Not exceed more than 120 words")]
        public string Description { get; set; }
        public string Body { get; set; }

        public virtual  List<Comments > Comments_List { get; set; }

    }

See here is the validation of each property. And also hold the list of comments. That means 1 blog contains many posts. So that is a one to many relationship.

The "Virtual" keywords means it will make the relationship.

4. Now in the Comments class write the following code:

public class Comments
    {
        [Key ]
        public int CommentId { get; set; }
          public string Comment { get; set; }
        //[ForeignKey]
          public int BlogId { get; set; }
          public virtual Blog Blog { get; set; }
 
    }


See here we also have the object reference of the "blog" class. Before that I have used the virtual key word.

5. Create a "DatabaseContext" folder under the project. After that create a class named "BlogDbContext.cs" under the folder. This class is an entity class.

6. Now make a reference for the Entity Framework by clicking "Add Reference" under the project.



In my project I had already provided the dll. Without this dll the table cannot be created in the database by object class mapping.

Now paste the following code into the "BlogDbContext" class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using blogmvc3.Models;

namespace blogmvc3.DatabaseContext
{
   
public class BlogDbContext:DbContext
    {
       
public DbSet<Blog> Blog { get; set; }
       
public DbSet<Comments> Comments { get; set; }
    }
}

See here in the Dbset we are passing a blog class and a comments class. The Dbset will create a table automatically with a relation in the database.

The Namespace "System.Data.Entity" is very important for that.

7. Now we have to configure the "web.config" file for the connection string. The web.config file is under the Main Solution Project. Not the Project web.config file.



Now paste the following connection string into the web.config file.

<connectionStrings>

    <add name="BlogDBContext" connectionString="data source=.;Database=Blogdb;Trusted_Connection=true;" providerName="System.Data.SqlClient" />
  </
connectionStrings>



8. Now create a Controller Class named "HomeController" under the "ControllerFolder. After that check the "Add action for create.update,delete.." so it will automatically create the action mrthod in the Controller class.





9. Now in the "HomeController" Class first create an object of the "BlogDbContext" Class.

BlogDbContext _db = new BlogDbContext();

After that in the Index Method write the following code:

public ActionResult Index()
        {
            return View(_db.Comments .ToList ());
        }

10. Now create a master page in the Razor engine under the "shared" folder. Give it the name "_LayoutPage1.cshtml".

After that paste the following code there:

<!DOCTYPE html>

<html>
<
head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
   @* <script src="../../Scripts/jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
    <link href="../../Content/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css" />
*@
</head>

<body>
    <div class="page">

        <div id="header">
            <div id="title">
                <h1>Blog Post</h1>
            </div>

            <div id="logindisplay">
                @*@Html.Partial("_LogOnPartial")*@
            </div>

            <div id="menucontainer">

                <ul id="menu">
                   @* <li>@html.actionlink("home", "index", "home")</li>*@
                    @*<li>@Html.ActionLink("About", "About", "Home")</li>*@
                   <li>@Html.ActionLink("home", "index", "home")</li>
                     <li>@Html.ActionLink("Article Post", "CreateLogin", "Article")</li>
                     @*<li>@Html.ActionLink("BookCab", "CreateLogin", "Cab")</li> *@
                </ul>

            </div>
             <script type="text/javascript"><!--                 mce: 0--></script>

        </div>

        <div id="main">
            @RenderBody()
            <div id="footer">
            </div>
        </div>
    </div>
</
body>
</
html>

11. Now go the "Home controller". Right-click the Index Method and add a view. It will look like:



Please check "Create Strongly-typed Views".

Choose Model Class "Comments" Under DropDown List.

Select "Scaffold Template" List. After that press the "Add" button. It will automatically create a view named "Index" under the "Home" folder.

12. See the Index View Engine will create code for the list view automatically.

Now delete all the code and replace it with the following code:

@model IEnumerable<blogmvc3.Models.Comments>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";

}
@{
    var grid = new WebGrid(source: Model, canPage: true, defaultSort: "BlogName", rowsPerPage: 3, canSort: true); 
    }

<h2>Web grid</h2>
if (@Model != null ) 

 {    

  @grid.GetHtml(tableStyle:"grid",headerStyle: "head",  alternatingRowStyle: "alt",caption:"WebGrid"
           )
 
 }

<p>

    @Html.ActionLink("Create New", "Create")
</p>

Now see this code section what is written above.



See first we are creating the WebGrid and after that in the constructor parameter we are passing a different property argument such as paging property, sorting, and rows per page.

And in the second we are are calling the WebGrid by calling the "@Html.WebGrid" property. Here also we are passing a parameter for the WebGrid.

Now run the application; it will look like the following figure:



See here the BlogId and Comments are displaying in the WebGrid (marked with red). And the paging facility is also done (marked with black).

Currently rated 2.8 by 31 people

  • Currently 2.806452/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: ASP.NET MVC 4.0 Mobile Template

clock November 16, 2011 15:22 by author darwin

Introduction

The five years back, we all are knew that  we able to developed ASP.NET mobile application usign Visual Studio, but microsoft  has been take off those templates from the visual studio in the following versions. But again there is a good news for all that Microsoft has released the much awaited ASP.NET MVC 4.0 developer preview and there are lots of features bundle with it. One of the greatest features is a mobile website. Yes, Now with ASP.NET MVC 4.0 you can create mobile site also. So let’s create a simple application and let’s see how it works.

To create mobile site first you need to click File->New Project->ASP.NET MVC 4.0 Web application. Like following.




Now once you click OK it will open a new another dialog like following where we have to choose the Mobile site.



As you can see in above post I have selected Razor view Once you click it will create a new application like following. As you can see similar structure as normal MVC Application application below.



This view are based on the standard jQuery Mobile. So this can be viewed in any tablet or mobile device. So if you have IPad and IPhone both then it will work on both. You need not to different application for both. see the browser first I have selected standard IPad size of browser.



Now lets see how it look in mobile. So I have made my browser same site as mobile. As you can see its working in both.



If you see the code of view you can see the razor syntax over there. Nothing change in razor syntax. But as you can see in below code you need to use Jquery mobile attributes like data-Role and other stuff which will convert standard HTML into mobile or device compatible website.

<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>


That's it. It’s very easy you can create mobile compatible site in few hours. Hope you like it.

Currently rated 1.9 by 20 people

  • Currently 1.85/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: How to Stream Files to Client in ASP.NET MVC 3

clock November 1, 2011 14:57 by author darwin

Streaming files to the client is very easy using ASP.NET MVC 3: The following code snippet shows an exemplary controller action "Download" that streams data to the client. If the client requests this action (e.g. by using the link [YOUR_CONTROLLER]/Download) the browser will (depending on it's settings) start downloading the data or open the download dialog.
The first optional parameter mimeType (e.g. "image/jpeg" for jpeg images or "application/pdf" for pdf documents) defines the HTTP header Content-type which is used by the browser to decide how to handle the data. The second optional parameter fileDownloadName defines the name of file the data should be saved to on the client's computer.

public ActionResult Download()
{
  var fileStream = [...];
  var mimeType = [...]; // optional
  var fileDownloadName = [...]; // optional
  return File(fileStream, mimeType, fileDownloadName);
}

Currently rated 2.7 by 6 people

  • Currently 2.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting on our European Data Center

clock October 31, 2011 16:46 by author Administrator

Starting from 7th Nov 2011, ASPHostCentral.com starts to offer a hosting service located in our prestigious Amsterdam (Netherland) Data Center. For further information, please click here.

For all our new customers who wish to have their sites activated on our Amsterdam (Netherland) data center, you must indicate your request on our order form at
https://secure.asphostcentral.com. For our existing customers, a one-time migration fee applies to all requests on our Amsterdam (Netherland) data center and please creates a ticket from our Help Desk to signal your interest.

Our new data center in Amsterdam provides businesses across Europe region. The Amsterdam data center is complemented by new points of presence (PoPs) in Europe that will provide millions of new users with a direct, dedicated path to our Network, providing lower latency and a superior end user experience.

Network Details

Our global network seamlessly integrates three distinct and redundant network architectures—Public, Private, and Data Center to Data Center—into the industry’s first Network-Within-a-Network topology for maximum accessibility, security, and control.

We leverage best-in-class connectivity and technology to innovate industry-leading, fully automated solutions that empower enterprises with complete access, control, security, and scalability. With this insightful strategy and our peerless technical execution, we have created the truly virtual data center—and made traditional hosting and managed/unmanaged services obsolete.

We are proud of our high speed connection. In fact, one of our most frequent compliments from our customers is how fast their site loads... read on and you will see why. When you combine high speed connectivity and high quality equipment, you get a fast and reliable web site. We have invested in the equipment and staff so you can rest assured that your site will load fast every time. We host sites all over the world, and with our multiple backbone connections, your customers will get through to your site fast.

For more details, please visit
ASPHostCentral.com website.

 

Currently rated 1.6 by 9 people

  • Currently 1.555556/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: ASP.NET MVC 4 Display Modes and WURFL.NET

clock October 30, 2011 17:52 by author darwin

The usage of mobile phones to access the web is increasing day by day. So, this is now become very important for every public web application to add the support of mobile browsers. ASP.NET MVC 4 makes it very easy for you to make the mobile phone user’s browsing experience as smooth as possible. For example, with Display Modes feature, you can select views depending on the browser(mobile or desktop) capabilities. But, ASP.NET MVC 4 does not include all the information about the capabilities of different mobile or desktop devices that are currently available on the market. For example, it does not tell you about the screen resolution of various mobile or desktop devices. WURFL(Wireless Universal Resource FiLe), is an up-to-date XML configuration file which contains the information about device capabilities. It contains over 7000 unique devices and thousands of firmware variations. WURFL.NET API(the one which is created by ScientiaMobile), currently, is the only .NET standard API for accessing WURLF data. WURFL.NET API contains information about devices in a list of over 500 capabilities. In this article, I will show you how you can use ASP.NET MVC 4  Display Modes feature with WURFL.NET API.

Description:

Firstly, create a new ASP.NET MVC 4 application. Next, open the Package Manager Console and type “Install-Package WURFL_Official_API”. This will add the WURFL.NET API in the application. You can also install the package using “Add Library Package Reference” dialog. Doing this will automatically add a reference to the WURFL.dll in the application. It will also add web_browsers_patch.xml and wurfl-latest.zip data files in App_Data folder. This step will make the WURFL.NET API available to the application.  


Now you need to tell WURFL.NET API about the location of web_browsers_patch.xml and wurfl-latest.zip data files. There are three ways to do this. First way: specify these data files in the web.config file,

        <wurfl>
            <mainFile path=”C:\….\WURFL.NETAndDisplayModes\App_Data\wurfl-latest.zip” />
            <patches>
              <patch path=”C:\….\WURFL.NETAndDisplayModes\App_Data\web_browsers_patch.xml” />
            </patches>
        </wurfl>

Note, you need to specify the complete path of data files. Currently, WURFL.NET API does not support any shortcuts(like, DataDirectory or ~). Next, you need add the following code inside the global.asax.cs file,


        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context.Cache);
        }
        public static void LoadWurflData(System.Web.Caching.Cache cache)
        {
            var configurer = new ApplicationConfigurer();
            var manager = WURFLManagerBuilder.Build(configurer);
            cache[WurflManagerCacheKey] = manager;
        }

Second way: instead of using web.config file, you can put all your code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        public const String WurflDataFilePath = “~/App_Data/wurfl-latest.zip”;
        public const String WurflPatchFilePath = “~/App_Data/web_browsers_patch.xml”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }

        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var wurflDataFile = server.MapPath(WurflDataFilePath);
            var wurflPatchFile = server.MapPath(WurflPatchFilePath);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Third way is the combination of first and second way. First, you need to add these app settings in web.config file,

        <add key=”WurflDataFilePath” value=”~/App_Data/wurfl-latest.zip” />
        <add key=”WurflPatchFilePath” value=”~/App_Data/web_browsers_patch.xml” />

Next, add the following code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }
        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var appSettings = WebConfigurationManager.AppSettings;
            var wurflDataFile = server.MapPath(appSettings["WurflDataFilePath"]);
            var wurflPatchFile = server.MapPath(appSettings["WurflPatchFilePath"]);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Now, WURFL.NET API is initialized. Let’s say you need to show a particular view depending on the device screen resolution. You can do this by adding the following code in Application_Start method, 

        DisplayModes.Modes.Insert(0, new DefaultDisplayMode(“Resolution320By480″)
        {
            ContextCondition = (context =>
            {
                var manager = (context.Cache[WurflManagerCacheKey] as IWURFLManager);
                var cabablities = manager.GetDeviceForRequest(context.Request.UserAgent);
                return cabablities.GetCapability(“resolution_width”) == “320″
                    && cabablities.GetCapability(“resolution_height”) == “480″;
            }
            )
        });


Now, if you make a request which returns the Index view, then ASP.NET MVC framework will look for Index.Resolution320By480.cshtml file for devices with 320X480 resolution and Index.cshtml file for others. Similarly, you can add different display modes in your application depending upon the various capabilities of device. WURFL.NET consists information in a list of over 500 capabilities.

Summary:

Using ASP.NET MVC 4 Display Modes feature, you can select views depending on the browser capabilities. WURFL.NET API provides you a list of over 500 capabilities. Combining both of these features will help you to build an application which support vast amount of devices. In this article, I showed you how you can add WURFL.NET API in your application. I also showed you how you can use WURFL.NET API to find the device capabilities and then use these capabilities in ASP.NET MVC 4 application. Hopefully you will enjoy this article too.

Currently rated 1.8 by 23 people

  • Currently 1.826087/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: Getting Started With ASP.NET MVC 4

clock October 3, 2011 20:46 by author Administrator
ASP.NET MVC 4 NuGet Packages

One good news is that MVC 4 is also available via NuGet. To install MVC 4 via NuGet, type following in the Package Manager Console.

For more detail regarding NuGet package please visit
http://www.nuget.org/List/Packages/AspNetMvc

ASP.NET MVC 4 for Visual Studio 2010

If you are using Visual Studio 2010 then you can use MVC 4 with Visual Studio 2010. To install MVC 4 via Web Platform Installer for Visual Studio 2010 please visit following link:
http://www.microsoft.com/web/gallery/install.aspx?appid=MVC4VS2010&prerelease=true

ASP.NET MVC 4 for Visual Studio 11 Developer Preview

If you are using Visual Studio 11 Developer Preview then you can install MVC 4 in Visual Studio 11 Developer Preview via following link:
http://www.microsoft.com/web/gallery/install.aspx?appid=MVC4VS11&prerelease=true

ASP.NET MVC 4 Direct Download Link

For Visual Studio 2010, first you need to install Visual Studio 2010 SP1 KB983509 via
http://download.microsoft.com/download/2/3/0/230C4F4A-2D3C-4D3B-B991-2A9133904E35/VS10sp1-KB983509.exe

MVC 4 Direct link for Visual Studio 2010

http://download.microsoft.com/download/E/D/7/ED7CB028-2CBD-4E26-87D5-C9164A0B4849/AspNetMVC4VisualStudio2010Setup.exe

MVC 4 Direct link for Visual Studio 11 Developer Preview
http://download.microsoft.com/download/E/D/7/ED7CB028-2CBD-4E26-87D5-C9164A0B4849/AspNetMVC4VisualStudio11Setup.exe

Useful Links

-
http://asp.net/mvc/mvc4 for latest update regarding MVC 4
-
http://forums.asp.net/1146.aspx ASP.NET MVC forum

Currently rated 1.9 by 17 people

  • Currently 1.941176/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Unlimited Domains Windows Hosting with ASPHostCentral.com

clock September 26, 2011 17:52 by author Administrator

A lot web hosting service providers will only allow you to host a single domain name on a single account. This works fine if you plan on having one website only. But later on when you need to setup additional websites, you will need to purchase a separate web hosting account for each of those additional websites. So for example, if you have 10 websites, you will need to pay for 10 web hosting accounts.

What's UNLIMITED Domain Hosting?

Unlimited Domain Hosting allows you to host unlimited number of domain names, or websites, under a single web hosting account. A hosting plan that allows unlimited Domain Hosting will definitely save you money since you can sign up for an account with one company and manage your websites from a central location.

Aside from saving you money, it also allows you to save time. Since all the domains would be hosted on the same hosting account, you can administer each domain simultaneously through the same control panel.

How Do I Take Advantage of Unlimited Domain Hosting?

The best way to get the most out of Unlimited Domain Hosting is to use an "unlimited" web hosting account. With ASPHostCentral.com, you can host any number of domains/websites under one single account and you can start from as low as $4.49/month only!

Currently rated 1.5 by 6 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4.0 Hosting :: Sneak Preview of ASP.NET MVC 4 Templates

clock September 26, 2011 17:14 by author Administrator

With release of ASP.NET MVC 4 Developer Preview, ASP.NET MVC team introduces a new default project template for MVC 4. New template has following improvements.

Cosmetic Improvements

New MVC 4 project template has cosmetic improvements prior to MVC 3 project template. And it will help community to create good looking modern websites with the default template itself without investing more in template designing.



Adaptive Rendering

Along with cosmetic improvements, new MVC 4 template used technique called Adaptive Rendering which will help in proper rendering in desktop browser as well mobile browser also without making any changes. To see Adaptive Rendering in action, resize browser window to be smaller and accordingly MVC 4 template layout will be changed to fit with screen size.


Rich UI

Another major improvement with MVC 4 default project template is use of JavaScript and jQuery plugins to provide rich UI. Click on Register and Login link to see rich UI in action.

  

Currently rated 2.3 by 13 people

  • Currently 2.307692/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: Working with ASP.NET MVC 4 Mobile Project Template

clock September 18, 2011 20:21 by author Administrator

With ASP.NET MVC 4, it’s even easier to setup and carry out a project which target mobile and tablet device. Yes MVC team introduce a new project template with MVC 4 which target mobile and tablet platform. This project template is build on the base of jQuery Mobile. And hence it is also optimized for better experience for touch screen

To get started with Mobile Project Template in MVC 4
Create a new ASP.NET MVC 4 Web Application
Select Mobile Application template when it ask to select project template

As far as the server side code (Controller, Model) is concern, it is same structured as Internet Application template. But responsibility of well rendering and well behavior for touch media is left on jQuery Mobile.

Inspecting Script folder of Internet Application Template and Mobile Project Template, you will find additional jquery.mobile-1.0b2.js file which is core script of jQuery Mobile included in Mobile Project Template of MVC 4.

Another major difference between Internet Application Template and Mobile Project Template is in its view. Inspecting _Layout.cshtml, you will notice some additional script reference and script in Mobile Project which is used by mobile or template device. In addition to script, another major difference in MVC 4 Mobile Project Template View is use of data-role and other attribute which is required for Mobile page structure and it used by mobile device and jQuery Mobile for proper rendering and behavior in touch screen and Smartphone

Currently rated 1.5 by 8 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3.0 Hosting :: Getting your ASP.NET MVC Application to return 404 HTTP Status Code

clock August 25, 2011 17:05 by author Administrator

ASP.NET MVC3 includes a new class HttpNotFoundResult in  System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?
First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
            var result = new HttpNotFoundResult();
            return result;
}


Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

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


we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
             return HttpNotFound("can not find requested resource");
}

Currently rated 1.5 by 70 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in