Menus

Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Saturday, December 22, 2012

WCF Service in an ASP.Net MVC Application

Introduction

In this article we will see how to access a WCF service and use it in our ASP.Net MVC application. In my previous articles we have seen the creation and consumtion of WCF services by a console client and a WPF client. In this article we will create the client as a MVC application.

For creating a WCF service you can read more over here. For this article we will create one simple WCF service which will return the dataset and in the MVC application we will simply access this WCF service and display the list of authors on the View. So let's start by creating the WCF service.

Creating WCF Author Service

Create a new WCF project in Visual Studio and name it AuthorService. When the service is created a default service will be created; delete it and add a new service to the project and name it ServiceAuthor which will create an 
IServiceAuthor Interface and a ServiceAuthor.cs class. Define one method in IServiceAuthor which returns a Dataset and in ServiceAuthor.cs implement the method which returns the dataset like below. Here I'm creating it on the fly but you can populate it from a database.

IServiceAuthor Code
public interface IServiceAuthor{
     [OperationContract]
     void DoWork();
     [OperationContract]
     DataSet ReturnAuthor();
}


ServiceAuthor.cs

   
public class ServiceAuthor : IServiceAuthor    {
        public void DoWork()
        {

        }
        public System.Data.DataSet ReturnAuthor()
        {
            DataSet ds = new DataSet();            DataTable dt = new DataTable("Author");
            DataColumn dc1 = new DataColumn("AuthorId"typeof(Int32));
            DataColumn dc2 = new DataColumn("Name"typeof(string));
            DataColumn dc3 = new DataColumn("Location"typeof(string));

            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            DataRow dr1 = dt.NewRow();
            dr1[0] = 10;
            dr1[1] = "Krishna Garad";
            dr1[2] = "India";
            dt.Rows.Add(dr1);
            DataRow dr2 = dt.NewRow();
            dr2[0] = 20;
            dr2[1] = "Mahesh Chand";
            dr2[2] = "USA";
            dt.Rows.Add(dr2);
            ds.Tables.Add(dt);
            return ds;
        }
    }

Now run the service application and copy the address.

Creating MVC client Application

Start a new MVC web application; add the controller in the controller folder with the name Home. Now add the service reference by right-clicking on the solution and selecting Service Reference and paste the copied address in the address box in the opened dialog like below.

wcfwithmvc.gif

Now we also have a service reference, so create the proxy for our WCF service like below in the Home controller.
ClientAuthorReference.ServiceAuthorClient obj = new ClientAuthorReference.ServiceAuthorClient();

Still now we have a proxy for our WCF service; now we can call the methods of our WCF service. On start up only we will show the AuthorList return from WCF service so in the Index Action write the following code and add the view to display the List of Authors.
public ActionResult Index()
{
     DataSet ds = obj.ReturnAuthor();
     ViewBag.AuthorList = ds.Tables[0];
     return View();
}
Add a view to display the list of Authors by looping over the DataTables which we supplied to ViewBag. Write the following code in your aspx page.
<table>        <tr><td>AuthorId</td><td>Name</td><td>Location</td></tr><%foreach (System.Data.DataRow dr in ViewBag.AuthorList.Rows)
  {%>    <tr> <td><%=dr["AuthorId"].ToString()%></td>        
         <td><%=dr["Name"].ToString() %></td>
<td><%=dr["Location"].ToString() %></td>    </tr>        
 <% } %> </table>

In the above markup we are simply reading each row and displaying on the page. Now run the application and view the Author List returned from WCF service.

Tuesday, December 4, 2012

Error Handling and CustomErrors and MVC3

MVC 3 now has a GlobalFilterCollection that is automatically populated with a HandleErrorAttribute. This default FilterAttribute brings with it a new way of handling errors in your web applications. In short, you can now handle errors inside of the MVC pipeline.
What does that mean?This gives you direct programmatic control over handling your 500 errors in the same way that ASP.NET and CustomErrors give you configurable control of handling your HTTP error codes.
How does that work out?Think of it as a routing table specifically for your Exceptions, it's pretty sweet!

Global Filters

The new Global.asax file now has a RegisterGlobalFilters method that is used to add filters to the new GlobalFilterCollection, statically located at System.Web.Mvc.GlobalFilter.Filters. By default this method adds one filter, the HandleErrorAttribute.
public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

HandleErrorAttributes

The HandleErrorAttribute is pretty simple in concept: MVC has already adjusted us to using Filter attributes for our AcceptVerbs and RequiresAuthorization, now we are going to use them for (as the name implies) error handling, and we are going to do so on a (also as the name implies) global scale.
The HandleErrorAttribute has properties for ExceptionType, View, and Master. The ExceptionType allows you to specify what exception that attribute should handle. The View allows you to specify which error view (page) you want it to redirect to. Last but not least, the Master allows you to control which master page (or as Razor refers to them, Layout) you want to render with, even if that means overriding the default layout specified in the view itself.
public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute
        {
            ExceptionType = typeof(DbException),
            // DbError.cshtml is a view in the Shared folder.
            View = "DbError",
            Order = 2
        });
        filters.Add(new HandleErrorAttribute());
    }

Error Views

All of your views still work like they did in the previous version of MVC (except of course that they can now use the Razor engine). However, a view that is used to render an error can not have a specified model! This is because they already have a model, and that is System.Web.Mvc.HandleErrorInfo
@model System.Web.Mvc.HandleErrorInfo
           
@{
    ViewBag.Title = "DbError";
}

<h2>A Database Error Has Occurred</h2>

@if (Model != null)
{
    <p>@Model.Exception.GetType().Name<br />
    thrown in @Model.ControllerName @Model.ActionName</p>
}

Errors Outside of the MVC Pipeline

The HandleErrorAttribute will only handle errors that happen inside of the MVC pipeline, better known as 500 errors. Errors outside of the MVC pipeline are still handled the way they have always been with ASP.NET. You turn on custom errors, specify error codes and paths to error pages, etc.
It is important to remember that these will happen for anything and everything outside of what the HandleErrorAttribute handles. Also, these will happen whenever an error is not handled with the HandleErrorAttribute from inside of the pipeline.
<system.web>
  <customErrors mode="On" defaultRedirect="~/error">
    <error statusCode="404" redirect="~/error/notfound"></error>
  </customErrors>

Sample Controllers

public class ExampleController : Controller
{
    public ActionResult Exception()
    {
        throw new ArgumentNullException();
    }
    public ActionResult Db()
    {
        // Inherits from DbException
        throw new MyDbException();
    }
}

public class ErrorController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult NotFound()
    {
        return View();
    }
}

Putting It All Together

If we have all the code above included in our MVC 3 project, here is how the following scenario's will play out:
  1. A controller action throws an Exception.
    • You will remain on the current page and the global HandleErrorAttributes will render the Error view.
  2. A controller action throws any type of DbException.
    • You will remain on the current page and the global HandleErrorAttributes will render the DbError view.
  3. Go to a non-existent page.
    • You will be redirect to the Error controller's NotFound action by the CustomErrors configuration for HTTP StatusCode 404.
But don't take my word for it, download the sample project and try it yourself.

Three Important Lessons Learned

For the most part this is all pretty straight forward, but there are a few gotcha's that you should remember to watch out for:
1) Error views have models, but they must be of type HandleErrorInfo.
It is confusing at first to think that you can't control the M in an MVC page, but it's for a good reason. Errors can come from any action in any controller, and no redirect is taking place, so the view engine is just going to render an error view with the only data it has: The HandleError Info model. Do not try to set the model on your error page or pass in a different object through a controller action, it will just blow up and cause a second exception after your first exception!
2) When the HandleErrorAttribute renders a page, it does not pass through a controller or an action.
The standard web.config CustomErrors literally redirect a failed request to a new page. The HandleErrorAttribute is just rendering a view, so it is not going to pass through a controller action. But that's ok! Remember, a controller's job is to get the model for a view, but an error already has a model ready to give to the view, thus there is no need to pass through a controller.
That being said, the normal ASP.NET custom errors still need to route through controllers. So if you want to share an error page between the HandleErrorAttribute and your web.config redirects, you will need to create a controller action and route for it. But then when you render that error view from your action, you can only use the HandlerErrorInfo model or ViewData dictionary to populate your page.
3) The HandleErrorAttribute obeys if CustomErrors are on or off, but does not use their redirects.
If you turn CustomErrors off in your web.config, the HandleErrorAttributes will stop handling errors. However, that is the only configuration these two mechanisms share. The HandleErrorAttribute will not use your defaultRedirect property, or any other errors registered with customer errors.

In Summary

The HandleErrorAttribute is for displaying 500 errors that were caused by exceptions inside of the MVC pipeline. The custom errors are for redirecting from error pages caused by other HTTP codes.

MVC3's GlobalFilters and HandleErrorAttribute

In MVC3 a GlobalFilterCollection has been added to the Application_Start. This allows you to register filters that will be applied to all controller actions in a single location. Also, MVC3 web applications now add an instance of HandleErrorAttribute to these GlobalFilters by default. This means that errors in the MVC pipeline will now be automatically handled by these attributes and never fire the HttpApplication's OnError event.
This is nice because it is another step away from the old ASP.NET way of doing things, and a step toward the newer cleaner MVC way of doing things. However, it did throw us a slight curve ball when updating CodeSmith Insight's HttpModule.

Out With the Old

Our old HttpModule wired up to the HttpApplication's OnError event and used that to log unhandled exceptions in web applications. It didn't care if the error happened in or out of the MVC pipeline, either way it was going to bubble up and get caught in the module.
public virtual void Init(HttpApplication context)
{
   InsightManager.Current.Register();
   InsightManager.Current.Configuration.IncludePrivateInformation = true;
   context.Error += OnError;
}

private void OnError(object sender, EventArgs e)
{
   var context = HttpContext.Current;
   if (context == null)
       return;

   Exception exception = context.Server.GetLastError();
   if (exception == null)
       return;

   var abstractContext = new HttpContextWrapper(context);
   InsightManager.Current.SubmitUnhandledException(exception, abstractContext);
}
However, now the MVC HandleErrorAttribute may handle exceptions right inside of the MVC pipeline, meaning that they will never reach the HttpApplication and the OnError will never be fired. What to do, what to do...

In With the New

Now we need to work with both the attributes and the HttpApplication, ensuring that we will catch errors from both inside and outside of the MVC pipeline. This means that we need to find and wrap any instances of HandleErrorAttribute in the GlobalFilters, and still register our model to receive notifications from the HttpApplications OnError event.
The first thing we had to do was create a new HandleErrorAttribute. Please note that this example is simplified and only overrides the OnException method. If you want to do this "right", you'll have to override and wrap all of the virtual methods in HandleErrorAttribute.
public class HandleErrorAndReportToInsightAttribute : HandleErrorAttribute
{
   public bool HasWrappedHandler
   {
       get { return WrappedHandler != null; }
   }

   public HandleErrorAttribute WrappedHandler { get; set; }

   public override void OnException(ExceptionContext filterContext)
   {
       if (HasWrappedHandler)
           WrappedHandler.OnException(filterContext);
       else
           base.OnException(filterContext);

       if (filterContext.ExceptionHandled)
           InsightManager.Current.SubmitUnhandledException(filterContext.Exception, 
filterContext.HttpContext);
   }
}
Next we needed to update our HttpModule to find, wrap, and replace any instances of HandleErrorAttribute in the GlobalFilters.
public virtual void Init(HttpApplication context)
{
   InsightManager.Current.Register();
   InsightManager.Current.Configuration.IncludePrivateInformation = true;
   context.Error += OnError;

   ReplaceErrorHandler();
}

private void ReplaceErrorHandler()
{
   var filter = GlobalFilters.Filters.FirstOrDefault(f => f.Instance is 
HandleErrorAttribute);
   var handler = new HandleErrorAndReportToInsightAttribute();

   if (filter != null)
   {
       GlobalFilters.Filters.Remove(filter.Instance);
       handler.WrappedHandler = (HandleErrorAttribute) filter.Instance;
   }

   GlobalFilters.Filters.Add(handler);
}

In Conclusion

Now when we register the InsightModule in our web.config, we will start capturing all unhandled exceptions again.
<configuration>
 <configSections>
   <section name="codesmith.insight" 
type="CodeSmith.Insight.Client.Configuration.InsightSection, 
CodeSmith.Insight.Client.Mvc3" />
 </configSections>
 <codesmith.insight apiKey="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" 
serverUrl="http://app.codesmithinsight.com/" />
 <system.web>
   <customErrors mode="On" />
   <httpModules>
     <add name="InsightModule" type="CodeSmith.Insight.Client.Web.InsightModule, 
CodeSmith.Insight.Client.Mvc3"/>
   </httpModules>
 </system.web>
</configuration>

MVC2 Unit Testing, Populating ModelState

Example Model and Controller
public class PersonModel
{
  [Required]
  public string Name { get; set; }
}
public class PersonController : Controller
{
  [AcceptVerbs(HttpVerbs.Get)]
  public ViewResult Register(Person person)
  {
    return View(new PersonModel());
  }
  [AcceptVerbs(HttpVerbs.Post)]
  public ViewResult Register(Person person)
  {
    if (!ModelState.IsValid)
      return View(model);
    PersonService.Register(person);
    return View("success");
  }
}
Example of the Problem
[Test]
public void RegisterTest()
{
  var model = new PersonModel { Name = String.Empty }; // This is model is invalid.
  var controller = new PersonController();
  var result = controller.Register(model);
  // This fails because the ModelState was valid, although the passed in model was not. 
  Assert.AreNotEqual("success", result.ViewName);
}
Solution
Other solutions I have come across were adding the errors to the model state manually, or mocking the ControllerContext as to enable the Controller's private ValidateModel method. I didn't like the former because it felt like I wasn't actually testing the model validation, and I didn't like the latter because it seemed like a lot of work to both mocking things and then still have to manually expose a private method.
My solution is (I feel) pretty simple: Add an extension method to the ModelStateDictionary that allows you to pass in a model, and it will then validate that model and add it's errors to the dictionary.
public static void AddValidationErrors(this ModelStateDictionary modelState, object model)
{
  var context = new ValidationContext(model, null, null);
  var results = new List<ValidationResult>();
  Validator.TryValidateObject(model, context, results, true);
  foreach (var result in results)
  {
    var name = result.MemberNames.First();
    modelState.AddModelError(name, result.ErrorMessage);
  }
}
Example of the Solution
[Test]
public void RegisterTest()
{
  var model = new PersonModel { Name = String.Empty }; // This is model is invalid.
  var controller = new PersonController();
  // This populates the ModelState errors, causing the Register method to fail and the unit test to pass.
  controller.ModelState.AddValidationErrors(model);
  var result = controller.Register(model);
  Assert.AreNotEqual("success", result.ViewName);
}

MVC 2 Client Side Model Validation with ExtJS

One of the most exciting new features in MVC 2 is "Enhanced Model Validation support across both server and client". The new enhanced support allows for client side validation to be dynamically generated into a view quickly and easily using DataAnnotations attributes on models. This means that by simply dressing up your model properties with attributes, your web pages can instantly have dynamic client side validation; all generated and maintained for you by the MVC framework!
MVC 2 enhanced model validation really is a terrific new feature...so, what's the problem? Microsoft uses JQuery, we use ExtJS.
We here at CodeSmith absolutely love MVC, but many of features are designed to use JQuery, and we (for several different reasons) prefer to use the ExtJS Framework. This means that (as it stands) to use both we must reference both, and no one wants to download two complete AJAX frameworks just to view one webpage.

Introducing: Ext.ux.MvcFormValidator
The MVC client side form validator dynamically generates a small blob of configuration for each form, and stores them in window.mvcClientValidationMetadata. Once the page loads up, the client side validator framework loads all these configs, and then starts monitoring the specified forms for validation.
What we have done is created an alternative form validation context (modeled after Sys.Mvc.FormContext) that loads the validation configuration, and requires no changes in the MVC generated code, but uses ExtJS as it's back end. This means that the only thing you have to do is reference Ext.ux.MvcFormValidator.js, and it will enable you to use the ExtJS Core for form validation instead of having to import MicrosoftMvcValidation and the other Microsoft AJAX libraries.

Features
  • Requires only the ExtJS Core.
  • Implements all four default validators: Required, Range, StringLength, RegularExpression
  • Supports integration of custom validators with almost no code change.
    • Just update Sys.Mvc.ValidatorRegistry.validators to call Ext.Mvc.ValidatorRegistry.validators
  • Displays field messages as well as summary.
  • Extends Ext.util.Observable and uses events.
  • Lightweight; less than 300 lines of code.
Example
Model
public class ValidationDemoModel
{
    [Required]
    [StringLength(10)]
    public string Name { get; set; }
    [Range(10000, 99999)]
    public string ZipCode { get; set; }
    [RegularExpression (@"\d{3}[-]?\d{3}[-]?\d{4}", ErrorMessage="The field Phone must be valid phone number.")]
    public string Phone { get; set; }
    [AcceptBox]
    public bool Accept { get; set; }
}
Site.Master
<script src="/Scripts/ext-core.js" type="text/javascript"></script>
<script src="/Scripts/Ext.ux.MvcFormValidator.js" type="text/javascript"></script>
<script src="/Scripts/CustomValidators.js" type="text/javascript"></script>
View
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Validation Demo</h2>
        <% Html.EnableClientValidation(); %>
        <% using (Html.BeginForm()) { %>
        <%= Html.LabelFor(m => m.Name) %>:
        <%= Html.TextBoxFor(m => m.Name)%>
        <%= Html.ValidationMessageFor(m => m.Name)%>
        <br />
        <%= Html.LabelFor(m => m.Phone) %>:
        <%= Html.TextBoxFor(m => m.Phone)%>
        <%= Html.ValidationMessageFor(m => m.Phone)%>
        <br />
        <%= Html.LabelFor(m => m.ZipCode) %>:
        <%= Html.TextBoxFor(m => m.ZipCode)%>
        <%= Html.ValidationMessageFor(m => m.ZipCode)%>
        <br />
        <%= Html.LabelFor(m => m.Accept) %>:
        <%= Html.CheckBoxFor(m => m.Accept)%>
        <%= Html.ValidationMessageFor(m => m.Accept)%>
        <br />
        <input type="submit" value="Submit" />
        <%  } %>
</asp:Content>
Controller Action
[HttpGet]
public ActionResult ValidationDemo()
{
    var model = new ValidationDemoModel();
    return View(model);
}
Custom Validator
Ext.Mvc.ValidatorRegistry.validators["acceptbox"] = function (rule) {
    return function (value, context) {
        return context.fieldContext.elements[0].checked === true;
    };
};

MVC JSON Model Binder

Asp.Net MVC JSON Model Binder!
Moving complex data structures from client to server used to be difficult, but not anymore! Just add the JsonBinder attribute to your action parameters, and this Custom ModelBinder will automatically detect the type and parameter name, and deserialize your complex JSON object to the data structure of your choice. No configuration required, it works every time, it's PFM (Pure Friendly Magic)!

JsonBinderAttribute Class
public class JsonBinderAttribute : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new JsonModelBinder();
    }
    public class JsonModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
                // Swap this out with whichever Json deserializer you prefer.
                return Newtonsoft.Json.JsonConvert.DeserializeObject(json, bindingContext.ModelType);
            }
            catch
            {
                return null;
            }
        }
    }
}
Example Business Objects
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    // Note: This property is not a primitive!
    public DomesticAnimal Pet { get; set; }
}
public class DomesticAnimal
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Species { get; set; }
}
Example JavaScript Code
var person = {
    Name : 'Tom',
    Age : 23,
    Pet : {
        Name : 'Buddy',
        Age : 12,
        Species : 'Canine'
    }
};
var url = 'Person/Update';
function jQueryTest() {
    var personJson = $.toJSON(person);
    $.post(url, { person : personJson });
}
function extJsTest() {
    var personJson = Ext.util.JSON.encode(person);
    Ext.Ajax.request({
            url : url,
            params : { person : personJson }
        });
}
Serialized JSON Post Param
person {"Name":"Tom","Age":23,Pet:{"Name":"Buddy",Age:12,Species:"Canine"}}
Example Controller (Where the magic happens!)
public class PersonController : Controller
{
    // Note: The JsonBinder attribute has been added to the person parameter.
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Update([JsonBinder]Person person)
    {
        // Both the person and its internal pet object have been populated!
        ViewData["PetName"] = person.Pet.Name;
        return View();
    }
}

Configuring MVC Routes in Web.config

ASP.NET MVC is even more configurable than you think!
Routes are registered in the Application Start of an MVC application, but there is no reason that they have to be hard coded in the Global.asax. By simply reading routes out of the Web.config you provide a way to control routing without having to redeploy code, allowing you to enable or disable website functionality on the fly.
I can't take credit for this idea, my implementation is an enhancement of Fredrik Normén's MvcRouteHandler that adds a few things that were missing:
  • Optional Parameters
  • Typed Constraints
  • Data Tokens
  • An MVC3 Library
Example Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    var routeConfigManager = new RouteManager();
    routeConfigManager.RegisterRoutes(routes);
}
Example Web.config
<configuration>
  <configSections>
    <section name="routeTable" type="MvcRouteConfig.RouteSection" />
  </configSections>
  <routeTable>
    <routes>
      <add name="Default" url="{controller}/{action}/{id}">
        <defaults controller="Home" action="Index" id="Optional" />
        <constraints>
          <add name="custom"
              type="MvcApplication.CustomConstraint, MvcApplication">
            <params value="Hello world!" />
          </add>
        </constraints>
      </add>
    </routes>
  </routeTable>

Friday, November 30, 2012

ASP.NET MVC Tutorial

ASP.NET is a development framework for building web pages and web sites with HTML, CSS, JavaScript and server scripting.
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.

The MVC Programming Model

MVC is one of three ASP.NET programming models.
MVC is a framework for building web applications using a MVC (Model View Controller) design:
  • The Model represents the application core (for instance a list of database records).
  • The View displays the data (the database records).
  • The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and JavaScript.

MVC
The MVC model defines web
applications with 3 logic layers:

The business layer (Model logic)
The display layer (View logic)
The input control (Controller logic)
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.

Web Forms vs MVC

The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.

Visual Web Developer

Visual Web Developer is the free version of Microsoft Visual Studio.
Visual Web Developer is a development tool tailor made for MVC (and Web Forms).
Visual Web Developer contains:
  • MVC and Web Forms
  • Drag-and-drop web controls and web components
  • A web server language (Razor using VB or C#)
  • A web server (IIS Express)
  • A database server (SQL Server Compact)
  • A full web development framework (ASP.NET)
If you install Visual Web Developer, you will get more benefits from this tutorial.
If you want to install Visual Web Developer, click on this link:
http://www.microsoft.com/web/gallery/install.aspx?appid=VWDorVS2010SP1Pack

What We Will Build

We will build an Internet application that supports adding, editing, deleting, and listing of information stored in a database.

What We Will Do

Visual Web Developer offers different templates for building web applications.
We will use Visual Web Developer to create an empty MVC Internet application with HTML5 markup.
When the empty Internet application is created, we will gradually add code to the application until it is fully finished. We will use C# as the programming language, and the newest Razor server code markup.
Along the way we will explain the content, the code, and all the components of the application.

Creating the Web Application

If you have Visual Web Developer installed, start Visual Web Developer and select New Project. Otherwise just read and learn.
New Project
In the New Project dialog box:
  • Open the Visual C# templates
  • Select the template ASP.NET MVC 3 Web Application
  • Set the project name to MvcDemo
  • Set the disk location to something like c:\w3schools_demo
  • Click OK
When the New Project Dialog Box opens:
  • Select the Internet Application template
  • Select the Razor Engine
  • Select HTML5 Markup
  • Click OK
Visual Studio Express will create a project much like this:
Mvc Explorer

MVC Folders

A typical ASP.NET MVC web application has the following folder content:
Solution  Application information
Properties
References
Application folders
App_Data Folder
Content Folder
Controllers Folder
Models Folder
Scripts Folder
Views Folder
Configuration files
Global.asax
packages.config
Web.config
The folder names are equal in all MVC applications. The MVC framework is based on default naming. Controllers are in the Controllers folder, Views are in the Views folder, and Models are in the Models folder. You don't have to use the folder names in your application code.
Standard naming reduces the amount of code, and makes it easier for developers to understand MVC projects.
Below is a brief summary of the content of each folder:

The App_Data Folder

The App_Data folder is for storing application data.
We will add an SQL database to the App_Data folder, later in this tutorial.

The Content Folder

The Content folder is used for static files like style sheets (css files), icons and images.
Visual Web Developer automatically adds a themes folder to the Content folder. The themes folder is filled with jQuery styles and pictures. In this project you can delete the themes folder.
Visual Web Developer also adds a standard style sheet file to the project: the file Site.css in the content folder. The style sheet file is the file to edit when you want to change the style of the application.
Content
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.

The Controllers Folder

The Controllers folder contains the controller classes responsible for handling user input and responses.
MVC requires the name of all controller files to end with "Controller".
Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):
Controllers
We will create more controllers later in this tutorial.

The Models Folder

The Models folder contains the classes that represent the application models. Models hold and manipulate application data.
We will create models (classes) in a later chapter of this tutorial.

The Views Folder

The Views folder stores the HTML files related to the display of the application (the user interfaces).
The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout pages).
Views
We will edit the layout files in the next chapter of this tutorial.

The Scripts Folder

The Scripts folder stores the JavaScript files of the application.
By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:
Scripts
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.

Adding a Layout

The file _Layout.cshtml represent the layout of each page in the application. It is located in the Shared folder inside the Views folder.
Open the file and swap the content with this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></script>
</head>
<body>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Movies", "Index", "Movies")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
<section id="main">
@RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
</body>
</html>

HTML Helpers

In the code above, HTML helpers are used to modify HTML output:
@Url.Content() - URL content will be inserted here.
@Html.ActionLink() - HTML link will be inserted here.
You will learn more about HTML helpers in a later chapter of this tutorial.

Razor Syntax

In the code above, the code marked red are C# using Razor markup.
@ViewBag.Title - The page title will be inserted here.
@RenderBody() - The page content will be rendered here.
You can learn about Razor markup for both C# and VB (Visual Basic) in our Razor tutorial.

Adding Styles

The style sheet for the application is called Site.css. It is located in the Content folder.
Open the file Site.css and swap the content with this:
body
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
border-bottom: 3px solid #cc9900;
font: Georgia, serif;
color: #996600;
}
#main
{
padding: 20px;
background-color: #ffffff;
border-radius: 0 4px 4px 4px;
}
a
{
color: #034af3;
}
/* Menu Styles ------------------------------*/
ul#menu
{
padding: 0px;
position: relative;
margin: 0;
}
ul#menu li
{
display: inline;
}
ul#menu li a
{
background-color: #e8eef4;
padding: 10px 20px;
text-decoration: none;
line-height: 2.8em;
/*CSS3 properties*/
border-radius: 4px 4px 0 0;
}
ul#menu li a:hover
{
background-color: #ffffff;
}
/* Forms Styles ------------------------------*/
fieldset
{
padding-left: 12px;
}
fieldset label
{
display: block;
padding: 4px;
}
input[type="text"], input[type="password"]
{
width: 300px;
}
input[type="submit"]
{
padding: 4px;
}
/* Data Styles ------------------------------*/
table.data
{
background-color:#ffffff;
border:1px solid #c3c3c3;
border-collapse:collapse;
width:100%;
}
table.data th
{
background-color:#e8eef4;
border:1px solid #c3c3c3;
padding:3px;
}
table.data td
{
border:1px solid #c3c3c3;
padding:3px;
}

The _ViewStart File

The _ViewStart file in the Shared folder (inside the Views folder) contains the following content:
@{Layout = "~/Views/Shared/_Layout.cshtml";}
This code is automatically added to all views displayed by the application.
If you remove this file, you must add this line to all views.

The Controllers Folder

The Controllers Folder contains the controller classes responsible for handling user input and responses.
MVC requires the name of all controllers to end with "Controller".
In our example, Visual Web Developer has created the following files: HomeController.cs (for the Home and About pages) and AccountController.cs (For the Log On pages):
Controllers
Web servers will normally map incoming URL requests directly to disk files on the server. For example: an URL request like "http://www.dotnetgig.blogspot.com/default.asp" will map directly to the file "default.asp" at the root directory of the server.
The MVC framework maps differently. MVC maps URLs to methods. These methods are in classes called "Controllers".
Controllers are responsible for processing incoming requests, handling input, saving data, and sending a response to send back to the client.

The Home controller

The controller file in our application HomeController.cs, defines the two controls Index and About.
Swap the content of the HomeController.cs file with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}

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

The Controller Views

The files Index.cshtml and About.cshtml in the Views folder defines the ActionResult views Index() and About() in the controller.

The Views Folder

The Views folder stores the files (HTML files) related to the display of the application (the user interfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending on the language content.
The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout pages).
 Views

ASP.NET File Types

The following HTML file types can be found in the Views Folder:
File TypeExtention
Plain HTML.htm or .html
Classic ASP.asp
Classic ASP.NET.aspx
ASP.NET Razor C#.cshtml
ASP.NET Razor VB.vbhtml

The Index File

The file Index.cshtml represents the Home page of the application. It is the application's default file (index file).
Put the following content in the file:
@{ViewBag.Title = "Home Page";}

<h1>Welcome to W3Schools</h1>

<p>Put Home Page content here</p>

The About File

The file About.cshtml represent the About page of the application.
Put the following content in the file:
@{ViewBag.Title = "About Us";}

<h1>About Us</h1>

<p>Put About Us content here</p>

Run the Application

Select Debug, Start Debugging (or F5) from the Visual Web Developer menu.
Your application will look like this:


Click on the "Home" tab and the "About" tab to see how it works.

Congratulations

Congratulations. You have created your first MVC Application.
Note: You cannot click on the "Movies" tab yet. We will add code for the "Movies" tab in the next chapters of this tutorial.

Creating the Database

Visual Web Developer comes with a free SQL database called SQL Server Compact.
The database needed for this tutorial can be created with these simple steps:
  • Right-click the App_Data folder in the Solution Explorer window
  • Select Add, New Item
  • Select SQL Server Compact Local Database *
  • Name the database Movies.sdf.
  • Click the Add button
* If SQL Server Compact Local Database is not an option, you have not installed SQL Server Compact on your computer. Install it from this link: SQL Server Compact
Visual Web Developer automatically creates the database in the App_Data folder.

Adding a Database Table

Double-clicking the Movies.sdf file in the App_Data folder will open a Database Explorer window.
To create a new table in the database, right-click the Tables folder, and select Create Table.
Create the following columns:
Column Type Allow Nulls
ID int (primary key) No
Title nvarchar(100) No
Director nvarchar(100) No
Date datetime No
Columns explained:
ID is an integer (whole number) used to identify each record in the table.
Title is a 100 character text column to store the name of the movie.
Director is a 100 character text column to store the director's name.
Date is a datetime column to store the release date of the movie.
After creating the columns described above, you must make the ID column the table's primary key (record identifier). To do this, click on the column name (ID) and select Primary Key. Also, in the Column Properties window, set the Identity property to True:
DB Explorer
When you have finished creating the table columns, save the table and name it MovieDBs.
Note:
We have deliberately named the table "MovieDBs" (ending with s). In the next chapter, you will see the name "MovieDB" used for the data model. It looks strange, but this is the naming convention you have to use to make the controller connect to the database table.

Adding Database Records

You can use Visual Web Developer to add some test records to the movie database.
Double-click the Movies.sdf file in the App_Data folder.
Right-click the MovieDBs table in the Database Explorer window and select Show Table Data.
Add some records:
ID Title Director Date
1 Psycho Alfred Hitchcock 01.01.1960
La Dolce Vita Federico Fellini 01.01.1960
Note: The ID column is updated automatically. You should not edit it.

Adding a Connection String

Add the following element to the <connectionStrings> element in your Web.config file:
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|\Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>

MVC Models

The MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic.
With MVC, models both hold and manipulate application data.

The Models Folder

The Models Folder contains the classes that represent the application model.
Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application security.
AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel.

Adding a Database Model

The database model needed for this tutorial can be created with these simple steps:
  • In the Solution Explorer, right-click the Models folder, and select Add and Class.
  • Name the class MovieDB.cs, and click Add.
  • Edit the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcDemo.Models
{
public class MovieDB
{
public int ID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
public DateTime Date { get; set; }

}
public class MovieDBContext : DbContext
{
public DbSet<MovieDB> Movies { get; set; }
}
}
Note:
We have deliberately named the model class "MovieDB". In the previous chapter, you saw the name "MovieDBs" (endig with s) used for the database table. It looks strange, but this is the naming convention you have to use to make the model connect to the database table.

Adding a Database Controller

The database controller needed for this tutorial can be created with these simple steps:
  • In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
  • Set controller name to MoviesController
  • Select template: Controller with read/write actions and views, using Entity Framework
  • Select model class: MovieDB (McvDemo.Models)
  • Select data context class: MovieDBContext (McvDemo.Models)
  • Select views Razor (CSHTML)
  • Click Add
Visual Web Developer will create the following files:
  • A MoviesController.cs file in the Controllers folder
  • A Movies folder in the Views folder

Adding Database Views

The following files are automatically created in the Movies folder:
  • Create.cshtml
  • Delete.cshtml
  • Details.cshtml
  • Edit.cshtml
  • Index.cshtml

Congratulations

Congratulations. You have added your first MVC data model to your application.
Now you can click on the "Movies" tab :-)
 

MVC Application Security

The Models Folder contains the classes that represent the application model.
Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application authentication.
AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel:
Model

The Change Password Model

public class ChangePasswordModel
{

[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2}      characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

}

The Logon Model

public class LogOnModel
{

[Required]
[Display(Name = "User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }

}

The Register Model

public class RegisterModel
{

[Required]
[Display(Name = "User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

HTML Helpers

With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.
Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In most cases, an HTML helper is just a method that returns a string.
With MVC, you can create your own helpers, or use the built in HTML helpers.

Standard HTML Helpers

MVC includes standard helpers for the most common types of HTML elements, like HTML links and HTML form elements.

HTML Links

The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.
With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.
Razor Syntax:
@Html.ActionLink("About this Website", "About")
ASP Syntax:
<%=Html.ActionLink("About this Website", "About")%>
The first parameter is the link text, and the second parameter is the name of the controller action.
The Html.ActionLink() helper above, outputs the following HTML:
<a href="/Home/About">About this Website</a>
The Html.ActionLink() helper as several properties:
PropertyDescription
.linkTextThe link text (label)
.actionNameThe target action
.routeValuesThe values passed to the action
.controllerNameThe target controller
.htmlAttributesThe set of attributes to the link
.protocolThe link protocol
.hostnameThe host name for the link
.fragmentThe anchor target for the link
Note: You can pass values to a controller action. For example, you can pass the id of a database record to a database edit action:
Razor Syntax C#:
@Html.ActionLink("Edit Record", "Edit", new {Id=3})
Razor Syntax VB:
@Html.ActionLink("Edit Record", "Edit", New With{.Id=3})
The Html.ActionLink() helper above, outputs the following HTML:
<a href="/Home/Edit/3">Edit Record</a>

HTML Form Elements

There following HTML helpers can be used to render (modify and output) HTML form elements:
  • BeginForm()
  • EndForm()
  • TextArea()
  • TextBox()
  • CheckBox()
  • RadioButton()
  • ListBox()
  • DropDownList()
  • Hidden()
  • Password()
ASP.NET Syntax C#:
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>

Publish Your Application Without Using Visual Web Developer

An ASP.NET MVC application can be published to a remote server by using the Publish commands in WebMatrix ,Visual Web Developer, or Visual Studio.
This function copies all your application files, controllers, models, images, and all the required DLL files for MVC, Web Pages, Razor, Helpers, and SQL Server Compact (if a database is used).
Sometimes you don't want to use this option. Maybe your hosting provider only supports FTP? Maybe you already have a web site based on classic ASP? Maybe you want to copy the files yourself? Maybe you want to use Front Page, Expression Web, or some other publishing software?
Will you get a problem? Yes, you will. But you can solve it.
To perform a web copy, you have to know how to include the right files, what DDL files to copy, and where store them.
Follow these steps:

1. Use the Latest Version of ASP.NET

Before you continue, make sure your hosting computer runs the latest version of ASP.NET (4.0).

2. Copy the Web Folders

Copy your website (all folders and content) from your development computer to an application folder on your remote hosting computer (server).
If your App_Data folder contains test data, don't copy the App_Data folder (see SQL Data below).

3. Copy the DLL Files

On the remote server create a bin folder in the root of your application. (If you have installed Helpers, you already have a bin folder)
Copy everything from your folders:
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies
to your application's bin folder on the remote server.

4. Copy the SQL Server Compact DLL Files

If your application has a SQL Server Compact database (an .sdf file in App_Data folder), you must copy the SQL Server Compact DLL files:
Copy everything from your folder:
C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Private
to your application's bin folder on the remote server.
Create (or edit) the Web.config file for your application:

Example C#

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />

<add invariant="System.Data.SqlServerCe.4.0"
name="Microsoft SQL Server Compact 4.0"
description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1,Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

</DbProviderFactories>
</system.data>
</configuration>

5. Copy SQL Server Compact Data

Do you have .sdf files in your App_Data folder that contains test data?
Do you want to publish the test data to the remote server?
Most likely not.
If you have to copy the SQL data files (.sdf files), you should delete everything in the database, and then copy the empty .sdf file from your development computer to the server.
THAT'S IT. GOOD CODING !