Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET

ASP.Net MVC Server Explorer (Part 1)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
18 Feb 2011CPOL9 min read 65.2K   2.3K   41   8
The Server Explorer is an application that introduces and explains how to use ASP.NET MVC and Visual Studio 2010 for web development

Overview

The application we’re building simply display server files as window explorer, and you can select folders or files to download.

image001.jpg

Double click a folder, will list all sub-folders and files.

image002.jpg

You can tick the checkbox to download folder and files you want.

image003.jpg

image004.png

1. Create ASP.Net MVC project

It’s not the focus of this article. We go through very quickly. We’ll start by selecting “New Project” from the File menu in Visual Web Developer. This brings up the New Project dialog. We’ll select the Visual C# -> Web Templates group on the left, then choose the “ASP.NET MVC 3 Empty Web Application” template. Name your project ServerExplorer and press the OK button.

This will create our project. The project includes folders: Content, Models, Controllers, and Views.

ASP.NET MVC makes use of some basic naming conventions for folder.

/Controllers

Controllers respond to input from the browser, decide what to do with it, and return response to the user.

/Views

Views hold our UI templates

/Models

Models hold and manipulate data

/Content

This folder holds our images, CSS, and any other static content

/Scripts

This folder holds our JavaScript files

/App_Data

This folder holds our database files

2. Models, Views, and Controllers

Web-based MVC frameworks map URLs to server code in a slightly different way. Instead of mapping incoming URLs to files, they instead map URLs to methods on classes. These classes are called "Controllers" and they are responsible for processing incoming HTTP requests, handling user input, retrieving and saving data, and determining the response to send back to the client (display HTML, download a file, redirect to a different URL, etc).

Adding Model

Before we create controller and views, we think about what’s the model you need. For ServerExploer, we need a model class which have basic file information, like file name, full path, last modified time, created time, etc.

Right-click the “Models” folder within the Solution Explorer and select “Add”, and then the “Class…” command. This will bring up the “Add New Item” dialog. Select Class Template. Name the class “FileModel” and press the Add button. This will create a new file, FileModel.cs. Add the following code to FileModel.cs.

C#
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

 

namespace ServerExplorer.Models

{

    public enum FileType

    {

        Folder,

        File,

        Zip,

        Exe,

        Music,

        Video,

        Xml,

        Picture,

        Dll,

        Config,

        FixedRoot,

        NetworkRoot,

        RemovableRoot,

        DiscRoot,

        SysRoot

    }

 

    public class Category

    {

        FileType value;

 

        public Category(FileType type)

        {

            value = type;

        }

 

        public FileType Value

        {

            get { return value; }

        }

 

        public override bool Equals(object obj)

        {

            if (obj is Category)

                return value.Equals((obj as Category).value);

            return base.Equals(obj);

        }

 

        public override string ToString()

        {

            switch (value)

            {

                case FileType.Folder:

                    return "Folder";

                case FileType.File:

                    return "File";

                case FileType.Zip:

                    return "Zip";

                case FileType.Config:

                    return "Config";

                case FileType.Dll:

                    return "Dll";

                case FileType.Exe:

                    return "Exe";

                case FileType.Music:

                    return "Music";

                case FileType.Picture:

                    return "Picture";

                case FileType.Video:

                    return "Video";

                case FileType.Xml:

                    return "Xml";

                case FileType.FixedRoot:

                    return "FixedRoot";

                case FileType.SysRoot:

                    return "SysRoot";

                case FileType.NetworkRoot:

                    return "NetworkRoot";

                case FileType.DiscRoot:

                    return "DiscRoot";

                case FileType.RemovableRoot:

                    return "RemovableRoot";

                default:

                    return "File";

            }

        }

    }

 

    public class FileModel

    {

        public string Extension { get; set; }

        public string Name { get; set; }

        public string Location { get; set; }

        public DateTime Created { get; set; }

        public DateTime Modified { get; set; }

        public DateTime Accessed { get; set; }

        public string FullPath { get; set; }

        public Category Category { get; set; }

 

        public FileModel(FileInfo fi)

        {

            Name = fi.Name;

            Modified = fi.LastWriteTime;

            Created = fi.CreationTime;

            Accessed = fi.LastAccessTime;

            Extension = fi.Extension.ToLower();

            Location = fi.DirectoryName;

            FullPath = Encode(fi.FullName);

            switch (Extension)

            {

                case ".exe":

                    Category = new Category(FileType.Exe);

                    break;

                case ".config":

                    Category = new Category(FileType.Config);

                    break;

                case ".dll":

                    Category = new Category(FileType.Dll);

                    break;

                case ".zip":

                    Category = new Category(FileType.Zip);

                    break;

                case ".xml":

                    Category = new Category(FileType.Xml);

                    break;

                case ".mp3":

                    Category = new Category(FileType.Music);

                    break;

                case ".wmv":

                    Category = new Category(FileType.Video);

                    break;

                case ".bmp":

                case ".jpg":

                case ".jpeg":

                case ".png":

                case ".gif":

                case ".cur":

                case ".jp2":

                case ".ami":

                case ".ico":

                    Category = new Category(FileType.Picture);

                    break;

                default:

                    Category = new Category(FileType.File);

                    break;
            }

         }
 

        public FileModel(DirectoryInfo di)

        {

            Name = di.Name;

            FullPath = Encode(di.FullName);

            Location = di.Parent != null ? di.Parent.FullName : "";

            Modified = di.LastWriteTime;

            Created = di.CreationTime;

            Accessed = di.LastAccessTime;

            Category = new Category(FileType.Folder);

        }


        public static string Encode(string filepath)

        {

            return filepath.Replace("\\", "/");

        }

 
        public static string Decode(string filepath)

        {

            return filepath.Replace("/", "\\");

        }
 

        public static IList<FileModel> GetRootDirectories()

        {

            List<FileModel> result = new List<FileModel>();

            DriveInfo[] drives = DriveInfo.GetDrives();

            string winPath = Environment.GetEnvironmentVariable("windir");

            string winRoot = Path.GetPathRoot(winPath);

            foreach (DriveInfo di in drives)

            {

                if (!di.IsReady)

                    continue;

                if (di.RootDirectory == null)

                    continue;

                if (di.RootDirectory.FullName == winRoot)

                {

                    result.Add(new FileModel(di.RootDirectory) { 
                        Category = new Category(FileType.SysRoot) });

                    continue;

                }

                switch (di.DriveType)

                {

                    case DriveType.CDRom:

                        result.Add(new FileModel(di.RootDirectory) {
                            Category = new Category(FileType.DiscRoot) });

                        break;

                    case DriveType.Fixed:

                        result.Add(new FileModel(di.RootDirectory) { 
                            Category = new Category(FileType.FixedRoot) });

                        break;

                    case DriveType.Network:

                        result.Add(new FileModel(di.RootDirectory) { 
                            Category = new Category(FileType.NetworkRoot) });

                        break;

                    case DriveType.Removable:

                        result.Add(new FileModel(di.RootDirectory) { 
                            Category = new Category(FileType.RemovableRoot) });

                        break;

                    default:

                        result.Add(new FileModel(di.RootDirectory));

                        break;

                }

                

            }

            return result;

        }
 

        public static IList<FileModel> GetFiles(string path)

        {

            List<FileModel> result = new List<FileModel>();

            if (string.IsNullOrEmpty(path))

            {

                return GetRootDirectories();

            }

            else

                path = Decode(path);

            try

            {

                string[] dirs = Directory.GetDirectories(path, "*.*", 
                    SearchOption.TopDirectoryOnly);

                foreach (string dir in dirs)

                {

                    DirectoryInfo di = new DirectoryInfo(dir);

                    result.Add(new FileModel(di));

                }

 

                string[] files = Directory.GetFiles(path, "*.*",

                                          SearchOption.TopDirectoryOnly);

 

                foreach (string file in files)

                {

                    FileInfo fi = new FileInfo(file);

                    result.Add(new FileModel(fi));

                }

                result.Sort((a, b) =>

                {

                    var name1 = a.Name;

                    var name2 = b.Name;

                    if (a.Category.Value == FileType.Folder)

                        name1 = " " + name1;

                    if (b.Category.Value == FileType.Folder)

                        name2 = " " + name2;

                    return name1.CompareTo(name2);

                });

                return result;

            }

            catch (Exception)

            {

            }

            return result;

        }

    }

}

Adding Explorer Controller

Right-click the “Controllers” folder within the Solution Explorer and select “Add”, and then the “Controller…” command. This will bring up the “Add Controller” dialog. Name the controller “ExplorerController” and press the Add button.

This will create a new file, ExplorerController.cs.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServerExplorer.Models;
 
namespace ServerExplorer.Controllers
{
    public class ExplorerController : Controller
    {
        //
        // GET: /Explorer/
 
        public ActionResult Index()
        {
            IList<FileModel> files = FileModel.GetFiles(null);
            return View(files);
        }
 
        public ActionResult LoadActionLinks(string path, List<string> list)
        {
            ViewData["CheckedList"] = list;
            return PartialView("ActionLinks", path);
        }
 
        public ActionResult GetFiles(string path)
        {
            IList<FileModel> files = FileModel.GetFiles(path);
            ViewData["Parent"] = path;
            return PartialView("FileList", files);
        }
 
        public ActionResult Download(string jlist)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = 
                new System.Web.Script.Serialization.JavaScriptSerializer();
            List<string> list = serializer.Deserialize<List<string>>(jlist);
            ZipResult result = new ZipResult();
            foreach (string path in list)
            {
                result.AddFile(FileModel.Decode(path));
            }
 
            return result;
        }
 
 
        public ActionResult GoUpper(string path)
        {
            string filePath = FileModel.Decode(path);
            IList<FileModel> files = new List<FileModel>();
            if (filePath == "root")
                files = FileModel.GetRootDirectories();
            else
                if (Directory.Exists(filePath))
                {
                    DirectoryInfo di = new DirectoryInfo(filePath);
                    if (di.Parent != null)
                    {
                        files = FileModel.GetFiles(di.Parent.FullName);
                        if (di.Parent.Parent != null)
                            ViewData["Parent"] = FileModel.Encode(
                                di.Parent.Parent.FullName);
                        else
                            ViewData["Parent"] = "root";
                    }
                    else
                    {
                        files = FileModel.GetRootDirectories();
                    }
                }
            return PartialView("FileList", files);
        }
 
        public ActionResult GoTop()
        {
            var files = FileModel.GetRootDirectories();
            return PartialView("FileList", files);
        }
    }
}

Adding View

Position the text cursor within the Index action method, then right-click and select “Add View”. This will bring up the Add View dialog.

When we click the add button, Visual Studio will create a new Index.aspx view template for us in the \Views\Explorer directory, creating the folder if doesn’t already exist.

The following is the code of index.aspx.

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ServerExplorer
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="listpane">
        <% Html.RenderPartial("FileList");%>
    </div>
</asp:Content>%>

Because we want dynamically update the File List content not the whole page, it uses Html.RenderPatial to render a View template, FileList.

Adding Partial View

ASP.NET MVC supports the ability to define Partial View templates that can be used to encapsulate View rendering logic for a sub-portion of a page. Partials provide a useful way to define View rendering logic once and then reuse it in multiple places across an application.

Right-click the “\Views\Shared” folder within the Solution Explorer and select “Add”, and then the “View…” command. This will display the “Add View” dialog. We’ll name the new View we want to create FileList, select the “Create a partial view” checkbox on the dialog, and indicate that we will pass it a FileModel class.

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

<script src="<%= Url.Content("~/Scripts/jQuery-1.4.4.js") %>" 
    type="text/javascript"></script>

<div id="commands">

   <% Html.RenderPartial("ActionLinks", ViewData["Parent"]);%>

</div>

 

<table id="listview">

    <tr class="noselect">

        <th id="one"/>

        <th id="two">

            Name

        </th>

        <th id="three">

            Date modified

        </th>

    </tr>

    <% foreach (var item in Model)

       { %>

    <tr  class="t-row noselect"">

        <td class="one">

            <%: Html.CheckBox("fileCheck", new {value = item.FullPath })%>

        </td>

        <td class="two">

            <img width="24" height="24" alt="<%= item.Category.ToString() %>" 
                src="<%= Url.Content("~/Content/Images/" + item.Category.ToString() + 
                    ".png") %>"

                style="vertical-align: middle;" />

            <span style="padding-left: 2px;">

                <%= item.Name %></span>

        </td>

        <td  class="three">

            <%: String.Format("{0:g}", item.Modified) %>

        </td>

        <td>

            <%= Html.Hidden("fullPath", item.FullPath) %>

        </td>

    </tr>

    <% } %>

</table>

 

<script type="text/javascript">

    $(function () {

        $.extend($.fn.disableTextSelect = function () {

            return this.each(function () {

                if ($.browser.mozilla) {//Firefox

                    $(this).css('MozUserSelect', 'none');

                } else if ($.browser.msie) {//IE

                    $(this).bind('selectstart', function () { return false; });

                } else {//Opera, etc.

                    $(this).mousedown(function () { return false; });

                }

            });

        });

        

    });

 

    $(document).ready(function () {

        $("#listview .t-row").click(function () {

            $("#listview tr").removeClass("t-state-selected");

            $(this).toggleClass("t-state-selected");

        });

 

        $("#listview .t-row").dblclick(function () {

            var path = getApplicationPath();

            var filename = jQuery("input[name=fullPath]", this).val();

            $.ajax({

                type: "POST",

                url: path + "Explorer/GetFiles",

                data: { path: filename },

                cache: false,

                dataType: "html",

                success: function (data) {

                    $('#listpane').html(data);

 

                }

            })

        });

 

        $(':checkbox').click(function () {

            var list = new Object;

            var i = 0;

            var filename = '<%= ViewData["Parent"] %>';

            var path = getApplicationPath();

            $("input:checkbox:checked").each(function () {

                list[i++] = $(this).val();

            });

            $.ajax({

                type: "POST",

                url: path + "Explorer/LoadActionLinks",

                data: { path: filename, list: list },

                cache: false,

                dataType: "html",

                success: function (data) {

                    $('#commands').html(data);

                }

            })

        });

        //No text selection on elements with a class of 'noSelect'
        $('.noselect').disableTextSelect(); 

        $("#listview .t-row:first").click(); 
 
    });

 

    function getApplicationPath() {

        var path = location.pathname;

        var index = path.indexOf("/Explorer");

        if (index > -1)

            return path.substr(0, index + 1);

        if (path.charAt(path.length - 1) != '/')

            path += '/';

        return path;

   }

</script>

We call another partial view template “ActionLinks” in FileList.ascx. That because we need dynamically partial update “ActionLinks” as well.

Right-click the “\Views\Shared” folder within the Solution Explorer and select “Add”, and then the “View…” command. This will display the “Add View” dialog. We’ll name the new View we want to create ActionLinks, select the “Create a partial view” checkbox on the dialog. The following code is ActionLinks.ascx.

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

<%

    bool upperEnabled = !string.IsNullOrEmpty(Model as string);

    List<string> list = ViewData["CheckedList"] as List<string>;

    string jList = "";

    if (list != null && list.Count > 0)

    {

        System.Web.Script.Serialization.JavaScriptSerializer serializer = 
            new System.Web.Script.Serialization.JavaScriptSerializer();

        jList = serializer.Serialize(list);

    }

 

    { %>

<p>

     <a id="top" <% if (upperEnabled)

            { %> href='javascript:goTop();' <% 

        } %> style="padding-left: .4em;"><span>Top</span></a>

    |

    <a id="upper" <% if (upperEnabled)

            { %> href='javascript:goUpper("<%= Model %>");' <% 

        } %> style="padding-left: .4em;"><span>Upper</span></a>

    |

    <a id="download" <% if (jList != "")

            { %> href='javascript:download();' <% 

        } %> style="padding-left: .4em;"><span>Download</span></a>

</p>

<%} %>

<script type="text/javascript">

    function goUpper(path) {

        $.ajax({

            type: "POST",

            url: getApplicationPath() + "Explorer/GoUpper",

            data: { path: path },

            cache: false,

            dataType: "html",

            success: function (data) {

                $('#listpane').html(data);
 
            }

        })

    }

 
    function goTop() {

        $.ajax({

            type: "POST",

            url: getApplicationPath() + "Explorer/GoTop",

            data: {},

            cache: false,

            dataType: "html",

            success: function (data) {

                $('#listpane').html(data);
 

            }

        })

    }

    function download() {

        var list = '<%= jList %>';

        var path = getApplicationPath() + "Explorer/Download/?jlist=" + list;

        window.location.href = path;

    }

</script>

In ActionLinks.ascx, it renders two links, one is “Upper” (go back to upper level folder) , the other is “Download”.

Disable an anchor tag

IE supports provides a half-baked implementation of the non-standard attribute 'disabled' on anchor tags ( it changes its colour -even though it does not actually disable the anchor (if it has an href value).  Firefox , Chrome do not provide any support for it. “Upper” link need to be disabled, if the current folder is top folder. “Download” link need to be enabled only when at least one checkbox checked.

The only way for all browsers to enable/disable the anchor is Add or remove the href attribute .

Look the above code, we add href attribute for both links with conditions. With magic tag “<% .. %>”, we can embed c# code even inside html element.

<a id="upper" <% if (upperEnabled)

            { %> href='javascript:goUpper("<%= Model %>");' <% 

        } %> style="padding-left: .4em;"><span>Upper</span></a>

Passing a .NET string list between java script and Server C# method

Server Explorer supports Multiple files (folders) download. That means you need pass a file full path string list to java script download function first, then the client function pass the list to C# server function via ajax.

But there is no IEnumerable in JavaScript, as you use it in .NET. There is something similar, but it is implemented completely differently. In .NET, IEnumerable just means the class provides a method, GetEnumerator(), which returns an IEnumerator (which itself only contains Current, MoveNext, and Reset methods). In JavaScript, when you do a iteration on an item, you are iterating over the names of its properties.

What you have to do is transform your data into a format that can be used by JavaScript. Most likely this means converting it into something called JSON. The easiest way to convert your .NET data into JSON is to use built-in libraries, such as JavaScriptSerializer.

In ActionLinks.ascx, we serialize ViewData[“CheckedList”] which is a .Net string list to a string with JavaScriptSerializer.

System.Web.Script.Serialization.JavaScriptSerializer serializer = 
    new System.Web.Script.Serialization.JavaScriptSerializer();
jList = serializer.Serialize(list);

Now we need access “jList” server global variable from javascript download function.

How to access server side variable from java script function in ASP.net MVC

You can access Model, ViewData or other variable like this.

var list = '<%= jList %>';

var model = '<%= Model %>';

var data = '<%= ViewData["blah"] %>';

The following code is download java script function.

function download() {
        var list = '<%= jList %>';
        var path = getApplicationPath() + "Explorer/Download/?jlist=" + list;
        window.location.href = path;
    }

We know any path in ASP.net MVC will be mapped to Controller class. The above code will be mapped to Download method of Explorer controller. We use URL query string format to pass parameters for this method. You also noted we use setting window.location.href to load a view or partial view. This will make the java script function exactly do the same thing as Html.ActionLink.

3. Partial Page Update with JQuery

In Server Explorer, when we double click a folder, sub-folders and files in this folder will be pop up to the list. Similar, when we check or uncheck the checkbox, action links need update as well (passing new view model to action links partial view).

$("#listview .t-row").dblclick(function () {
            var path = getApplicationPath();
           var filename = jQuery("input[name=fullPath]", this).val();
            $.ajax({
                type: "POST",
                url: path + "Explorer/GetFiles",
                data: { path: filename },
                cache: false,
                dataType: "html",
                success: function (data) {
                    $('#listpane').html(data);
 
                }
            })
        });

The controller method is:

public ActionResult GetFiles(string path)
        {
            IList<FileModel> files = FileModel.GetFiles(path);
            ViewData["Parent"] = path;
            return PartialView("FileList", files);
        }

The client double click event handler call GetFiles method in Explorer controller via JQuery .ajax method. GetFiles returns a PartialView action result. When client get the result, it will update listpane div.

The following code will partial update action links when check or uncheck the checkbox.

$(':checkbox').click(function () {
            var list = new Object;
            var i = 0;
            var filename = '<%= ViewData["Parent"] %>';
            var path = getApplicationPath();
            $("input:checkbox:checked").each(function () {
                list[i++] = $(this).val();
            });
            $.ajax({
                type: "POST",
                url: path + "Explorer/LoadActionLinks",
                data: { path: filename, list: list },
                cache: false,
                dataType: "html",
                success: function (data) {
                    $('#commands').html(data);
                }
            })
        });
 
        //No text selection on elements with a class of 'noSelect'
        $('.noselect').disableTextSelect(); 
        $("#listview .t-row:first").click(); 
 
    });

The controller method is:

public ActionResult LoadActionLinks(string path, List<string> list)
        {
            ViewData["CheckedList"] = list;
            return PartialView("ActionLinks", path);
        }

One thing maybe we need bring up is we don’t have to declare an event handler in html. We use JQuery to bind anonymous event handler to a html element.

4. ASP.Net Custom Action Result

One of ASP.Net MVC benefit is how easy to build a custom action result. Although there is a FileResult in MVC already, we need do more in Server Explorer download. Because we support multiple folders and files download, one idea is add these selected files or folders to a zip archive. If we only select one file, and the file is zip file already, don’t do the redundant zip again.

All these stuff we can do it in a custom action result.

Add a class in Controller folder, and name it as ZipResult.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace ServerExplorer.Controllers
{
    public class ZipResult : ActionResult
    {
        List<string> archives = new List<string>();
 
        public override void ExecuteResult(ControllerContext context)
        {
            if (archives.Count == 0)
                return;
            string zipName;
            bool zipped = false;
            if (archives.Count == 1)
            {
                if (Path.GetExtension(archives[0]) == ".zip")
                    zipped = true;
                zipName = Path.GetFileNameWithoutExtension(archives[0]) + ".zip";
            }
            else
                zipName = String.Format("archive-{0}.zip",
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            context.HttpContext.Response.Buffer = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("content-disposition", 
                "attachment; filename=" + zipName);
            context.HttpContext.Response.ContentType = "application/zip";
            if (zipped)
                context.HttpContext.Response.WriteFile(archives[0]);
            else
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string path in archives)
                    {
                        try
                        {
                            FileAttributes attr = System.IO.File.GetAttributes(path);
 
                           if ((attr & FileAttributes.Directory) == 
                               FileAttributes.Directory)

                               zip.AddDirectory(path, 
                                   Path.GetFileNameWithoutExtension(path));
                            else
                                zip.AddFile(path, "");
                        }
                        catch (Exception)
                        {
                        }
                    }
                    zip.Save(context.HttpContext.Response.OutputStream);
                }
            }
        }
 
        public void AddFile(string filepath)
        {
            archives.Add(filepath);
        }
 
    }
}

You can find a lot free and open source Zip utilities. We use Ionic Zip here.

The following code is Download method in Explorer controller.

C#
public ActionResult Download(string jlist)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = 
                new System.Web.Script.Serialization.JavaScriptSerializer();
            List<string> list = serializer.Deserialize<List<string>>(jlist);
            ZipResult result = new ZipResult();
            foreach (string path in list)
            {
                result.AddFile(FileModel.Decode(path));
            }
 
            return result;
        }

5.Deploy ASP .Net MVC3 to IIS7

First, ASP .Net MVC3 is using .Net Framework 4. So please make sure .Net Framework 4 is installed on the deployed target machine.

You don’t have to install ASP.net MVC3 on the target machine, if change the dependant assemblies reference property “Copy Local” to true.

The below listed ASP .net MVC3 dependent assemblies:

C#
System.Web.Abstractions

System.Web.Extensions

System.Web.Helpers

System.Web.Mvc

System.Web.Razor

System.Web.Routing

Microsoft.Web.Infrastructure

System.Web.WebPages

System.Web.WebPages.Razor

Create an Application Pool with .Net Framework 4

Open IIS manager, right click “Application Pools”, select “Add Application Pool” command. It will bring up Add Application Pool dialog, select .Net Framework v4.0 in .Net Framework version dropdown list.

image005.png

Add an application in target website

Right click the target web site, select “Add Application” command. It will bring up “Add Application” Dialog. Select the application pool which created for this application.

image006.png

Deploy ASP .net MVC3 Application to IIS 7 from Visual Studio 2010

There are couple of ways to deploy web application to IIS 7. But I prefer deploy it from VS2010 with ftp publish. First you need enable ftp publishing for the target site in IIS 7. Right Click the project , select “publish” command. It’ll bring up Publish Web dialog.

image007.png

Select “FTP” as publish method, and type the target location.

Re-install .Net Framework 4 for IIS7

For some reasons (mostly happens for IIS 7 installed before .Net 4), after you publish your ASP.Net MVC3 web application to the target web site, it doesn’t work at all. When you browse your application in a browser, you’ll get an error like “Directory Browsing not enabled”. Then if you enable “Directory Browsing”, your application is still not running instead of listing directory contents in browser.

If that happens, that means .Net Framework 4.0 not installed properly on your IIS 7. You need re-install it.

Open Command Prompt .

Go to Windows\Microsoft.NET\Framework\v4.0.30319 or Windows\Microsoft.NET\Framework64\v4.0.30319 folder.

Type the following command:

aspnet_regiis –i

After re-installation, your application will work as expected.

Conclusion

We’ve seen that that ASP.NET MVC makes it easy to create a website pretty quickly. Hopefully this article has given you the tips you need to get started building your own ASP.NET MVC applications!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
Fred is a senior software developer who lives in Melbourne, Australia. In 1993, he started Programming using Visual C++, Visual Basic, Java, and Oracle Developer Tools. From 2003, He started with .Net using C#, and then expertise .Net development.

Fred is often working with software projects in different business domains based on different Microsoft Technologies like SQL-Server, C#, VC++, ASP.NET, ASP.Net MVC, WCF,WPF, Silverlight, .Net Core and Angular, although he also did some development works on IBM AS400.

Comments and Discussions

 
QuestionCannot read configuration file due to insufficient permissions.. Pin
Manik Lochan3-Mar-13 3:03
Manik Lochan3-Mar-13 3:03 
Questionerror message Pin
Arif Sattaur9-Jan-13 4:04
Arif Sattaur9-Jan-13 4:04 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey18-Jul-12 19:58
professionalManoj Kumar Choubey18-Jul-12 19:58 
Bug(Very) Little problem Pin
Manuel Cardoso26-Jan-12 12:30
Manuel Cardoso26-Jan-12 12:30 
GeneralMy vote of 5 Pin
Rajesh Pillai4-May-11 6:52
Rajesh Pillai4-May-11 6:52 
GeneralMy vote of 5 Pin
nodar22-Feb-11 5:56
nodar22-Feb-11 5:56 
GeneralMy vote of 3 Pin
jszczur21-Feb-11 5:40
jszczur21-Feb-11 5:40 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)18-Feb-11 11:01
Eric Xue (brokensnow)18-Feb-11 11:01 
Great effort, mate! Thanks for putting this up as a CP article to share with us. Btw, it seems that your article is missing a few images and clumsy formatting, but the rest is all good. Keep up with your good work and look forward to your next article!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.