European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: How to Create Mobile-Friendly HTML5 Forms with ASP.NET MVC 4

clock December 20, 2012 05:22 by author Scott

Mobilized Web Project Templates in Visual Studio 2010

The MVC 4 Mobile project template in Visual Studio 2010 contains all the files and references necessary to create a mobile-friendly Web site. When you create a new MVC 4 Mobile project, you’ll notice the familiar Models, Views and Controllers folders requisite for all MVC 4 projects (mobile or not) alongside new or modified scripts in the \Scripts folder. The \Scripts folder is where you’ll find the many jQuery files that serve as an API for building mobile-friendly Web sites, in particular, the jquery.mobile-1.0b2.js file for development and its minified partner, jquery.mobile-1.0b2.min.js, for deployment.

The \Content folder contains the location for style sheets, images and design-related files. Keep in mind that the jquery.mobile-1.0b2.css style sheet defines a look and feel that specifically targets multiple mobile platforms. (See http://jquerymobile.com/gbs/ for a list of supported mobile and tablet platforms.) Much like JavaScript files, there are two style sheets: a fat version for development and a minified version for production.

Data Sources for HTML5 Forms: MVC 4 Models and ViewModels

Regardless of whether the target is mobile or desktop, HTML5 form elements map to a property of an entity in a model or a ViewModel. Because models expose varied data and data types, their representation in the user interface requires varied visual elements, such as text boxes, drop-down lists, check boxes and buttons. You can see the full set of available controls or elements at the jQuery Mobile Web site’s Form Element Gallery.

Simple forms that contain only text inputs and buttons are not the norm. Most forms have several types of data. Because of this data variety, coding and maintenance will be easier if you use a ViewModel. ViewModels are a combination of one or more types that together shape data that goes to the view for consumption and rendering.

Let’s say you want to build a quick way for users of your Web site to provide feedback. You need to collect the user’s name, the type of feedback the user wants to leave, the comment itself, and the priority of the comment—that is, whether or not it’s urgent. Figure 1 shows how the FeedbackModel class definition captures these features in simple data structures such as strings, an int, and a Boolean.

public class FeedbackModel
{
    public string CustomerName { get; set; }
    public int FeedbackType { get; set; }
    public string Message { get; set; }
    public bool IsUrgent { get; set; }
}

Figure 1 Feedback Model

The FeedbackType property in Figure 1 is of type int, and it corresponds to the value the user selects at run time in the feedback type drop-down list defined in Figure 3.

Figure 2 contains the definition for the FeedbackViewModel, which is a combination of the FeedbackModel described in Figure 1 and the FeedbackType class (described in Figure 3).

public class FeedbackViewModel
{
    public FeedbackModel Feedback { get; set; }
    public FeedbackType FeedbackType { get; set; }        
    public FeedbackViewModel()
    {
        Feedback = new FeedbackModel();
        FeedbackType = new FeedbackType();
    }
}

Figure 2 Feedback ViewModel Containing the FeedbackModel and FeedbackType Properties

The use of the FeedbackType property highlights the purpose of ViewModels, which, as I mentioned earlier, is to shape disparate data sources or models together to form a single consumable source from the view, using strongly typed syntax.

While you can represent most of the data in a simple ViewModel as text boxes or check boxes, you also need to capture the type of feedback, which is a list of name-value pairs exposed in code as a more complex dictionary object. Figure 3 shows the FeedbackType class and the dictionary contained within it.

public class FeedbackType
{
    public static SelectList FeedbackSelectList
    {
        get { return new SelectList(FeedbackDictionary, "Value", "Key"); }
    }
    public static readonly IDictionary<string, int> 
         FeedbackDictionary = new Dictionary<string, int> 
    { 
        { "Select the type ...", 0 },
        { "Leave a compliment", 1 },
        { "Leave a complaint", 2 },
        { "Leave some SPAM", 3 },
        { "Other", 9 }
    };
}

Figure 3 FeedbackType Class, Including User Feedback Types

Now that the ViewModel is complete, the controller must pass it to the view for rendering. This straightforward code is in Figure 4 and is virtually identical to code that passes back a model.

public ActionResult Feedback()
{
    FeedbackViewModel model = new FeedbackViewModel();
    return View(model);
}

Figure 4 Controller Passing the ViewModel to the View

The next step in the process is setting up the view.

Creating HTML5 Mobile Forms in ASP.NET MVC 4 Views

You use the standard Add New Item command in Visual Studio 2010 to create feedback.cshtml, the view that will host your HTML5 form. ASP.NET MVC 4 favors a development technique named convention over configuration, and the convention is to match the name of the action method (Feedback) in the controller in Figure 4 with the name of the view, that is, feedback.cshtml. You can find the Add New Item command from the shortcut menu in Solution Explorer or the Project menu.

Inside the view, various ASP.NET MVC 4 Html Helpers present components of the FeedbackViewModel by rendering HTML elements that best fit the data types they map to in the ViewModel. For example, CustomerName renders as a standard single-line text box, while the Message property renders as a text area. FeedbackType renders as an HTML drop-down list so that the user can easily select an item rather than manually enter it. Figure 5 shows that there is no lack of Html Helpers to choose from for building forms.

@using (Html.BeginForm( "Results","Home")) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Leave some feedback!</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Feedback.CustomerName)
            @Html.ValidationMessageFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Feedback.FeedbackType, 
                 FeedbackType.FeedbackSelectList) 
            @Html.ValidationMessageFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.Message)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Feedback.Message)
            @Html.ValidationMessageFor(model => model.Feedback.Message)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.IsUrgent)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Feedback.IsUrgent)
            @Html.ValidationMessageFor(model => model.Feedback.IsUrgent)
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Figure 5 Html Helpers

With the ViewModel, controller and view, the form is now ready to test in the browser.

Testing the HTML Form on the Windows Phone 7 Emulator

Running a browser from Visual Studio is the easiest way to test the form, but the look and feel doesn’t behave in a very mobile-like way. For viewing the output and testing the form, the Windows Phone 7 Emulator works perfectly.

The HTML5 form displays in the Windows Phone 7 Emulator, as shown in Figure 6. You can enter a name, select a type from the drop-down list, fill in the comments and submit the form. Without modifications to the default styling provided by jQuery Mobile style sheets, the overall HTML5 form looks like the image on the left side of Figure 6. After tapping on the drop-down, the list of items looks like the image on the right side of Figure 6. Tapping a list item to select it returns the user to the form.

Figure 6 Interacting with the Windows Phone 7 Emulator

Submitting the form directs the browser to send the form information to the Home controller because of the call to the Html Helper, Html.BeginForm( "Results","Home"). The BeginForm method directs the HTTP request to the HomeController controller and then runs the Results action method, as the arguments denote.

Before the form submission process sends the HTTP Request to the server, however, client-side validation needs to happen. Annotating the data model accomplishes this task nicely. In addition to validation, data annotations provide a way for the Html.Label and Html.LabelFor helpers to produce customized property labels. Figure 7 details the entire data model with attributes for both validation and aesthetic annotations, and Figure 8 illustrates their results in the Windows Phone 7 Emulator.

public class FeedbackModel
{
    [Display(Name = "Who are you?")]
    [Required()]
    public string CustomerName { get; set; }
    [Display(Name = "Your feedback is about...")]
    public int FeedbackType { get; set; }
    [Display(Name = "Leave your message!")]
    [Required()]
    public string Message { get; set; }
    [Display(Name = "Is this urgent?")]
    public bool IsUrgent { get; set; }
}

Figure 7 Complete Data Model with Annotations

Figure 8 Left: Data Annotation Validations; Right: Data Annotation Aesthetics

You can customize the error message of the Required attribute to make the user interface friendlier. There are also many more annotations available in the System.Data.DataAnnotations namespace. If you can’t find a data annotation that fits your validation, aesthetic or security needs, inheriting from the System.Attribute class and extending it gives you that flexibility.

From the Phone to the Server Through HTTP POST

Once the user taps the submit button on the phone—and assuming the form passes validation—an HTTP POST Request is initiated and the data travels to the controller and action method designated in the Html.BeginForm method (as was shown in Figure 5). The sample from Figure 9 shows the controller code that lives in the HomeController and processes the data that the HTTP Request sends. Because of the power of ASP.NET MVC 4 model binding, you can access the HTML form values with the same strongly typed object used to create the form – your ViewModel.

[HttpPost()]
public ActionResult Results(FeedbackViewModel model)
{
    // calls to code to update model, validation, LOB code, etc...
    return View(model);
}

Figure 9 Capturing the HTTP POST Data in the Controller

When capturing HTTP POST data, data annotations once again assist in the task, since action methods that have no attribute stating the type of HTTP verb default to HTTP GET. 

Conclusion

Creating shiny new forms for mobile devices as well as desktops has never been easier with the partnership between ASP.NET MVC 4, jQuery Mobile and HTML5.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Installation Error - Incompatible with .NET 4.5

clock November 1, 2012 09:22 by author Scott

Introduction

When you install ASP.NET MVC 4 for Visual Studio 2010, If you are already using 4.5 framework in your box then you might get some strange errors.

Background

In this case I already having .NET Framework 4.5 RC and I want to install ASP.NET MVC 4 for Visual Studio 2010.

I tried using the standalone installer for ASP.NET MVC 4 for Visual Studio 2010 but it throws me below error



Yes, you’ll see this strange error.
  The error said that Visual Studio 2010 needs .NET Framework 4.5. So, how to fix this error.

Solution


To resolve this issue I removed the .NET Framework
4.5 RC from local box.



And the second is uninstalling the .NET Framework 4.5 also removes pre-existing .NET Framework 4 files. If you want to go back to the .NET Framework 4, you must reinstall it and any updates to it.


If you are not installing .NET Framework 4.0 after uninstallation of Framework 4.5 then you will get another error saying something like 'Framework 4.0 not found".

Hope it helps!



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Upgrade ASP.NET MVC 3 Project to ASP.NET MVC 4 Project

clock October 24, 2012 11:02 by author Scott

ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, We can run both version of ASP.NET MVC projects on same machine.

If we would like upgrade an ASP.NET MVC 3 Project to ASP.NET MVC 4 Project, they are multiple ways. The simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match the old project. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.


To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:


1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):


System.Web.Mvc, Version=3.0.0.0

System.Web.WebPages, Version=1.0.0.0
System.Web.Helpers, Version=1.0.0.0
System.Web.WebPages.Razor, Version=1.0.0.0

with the following corresponding text:


System.Web.Mvc, Version=4.0.0.0

System.Web.WebPages, Version=2.0.0.0
System.Web.Helpers, Version=2.0.0.0
System.Web.WebPages.Razor, Version=2.0.0.0

2. In the root Web.config file, update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "
true":



3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 (RC) package, Click OK.


4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.


5. Locate the ProjectTypeGuids element and replace
{E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.

6. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:




Looking for ASP.NET MVC 4 Hosting? Find an affordable ASP.NET MVC 4 Hosting with HostForLIFE.eu

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET Single Page Application

clock October 22, 2012 09:23 by author Scott

What is Single Page Application?

Single Page Application is an architecture for web applications. It combines the best of web and desktop, built with HTML5 and JavaScript.Single Page Applications are rich and responsive. You do not need any browser plug-ins needs to install for this architecture, it is a standard web technology that is going to work on any device, operating system and browser.

The reference for this post is http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159 from Steve Sanderson’s Techdays talk,

You can develop Single Page Applications using ASP.NET MVC\Web Forms technologies.

Benefits

1. Great user experience
– It means speed, when it comes to changing of display of user interface and navigate around, we want an instance response from the application which you can get from this architecture.

2. Run on any device

3. Working off-line
– It is an interesting benefit which is just becoming possible now.

4. App-store deployable
- It is bit advanced programming but you can deploy your applications to windows market place or Apple app-store etc. This is now possible with Phone-gap third party tool for developing apps for mobiles.

The Architecture diagram looks as below



Typical Web architecture contains a server and client, where server contains an endpoint to server HTML/CSS and JS. The client side this being rendered as Visible UI and contains some javascript as well that is web technology.


What is different in Single Page Applications?

With single page web applications, you also tend to have an data end points on server and it is going to return JSON\XML to your application, You can use this data on client data access layer and render that data to UI.


We also want to have fast UI navigation, to done that we have Navigation API which allows you to book marking, navigate forth and back without talking to the server.

We can also make available all right hand side in the diagram offline. You can use local storage apis in HTML5 to work with the data offline.

Using the new Single Page Application project template and scaffolder

Create a new ASP.NET MVC application in Visual Studio, You can install MVC4 beta from here.



It will prompt you to select the project template there you can select Single Page Application project template as shown below



It creates a MVC application but the difference is it creates additional javascript libraries to make it easier for you build single page applications. If you want to use scaffolding then you can use a model class named TodoItem which will be created for you in model folder

To build a sample Single Page application using scaffolding, Add a controller to your solution



Choose the Single Page application template in controller dialogue box



Now run the application then you should be able to see the below output



What is different from other scaffolding applications is it follows single page application architecture and when you hit the browser back and forward it would not talk to the server. It also follows the all principles that we discussed on top.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Implementing custom XmlMediaTypeFormatter that ignores XML namespaces in ASP.NET MVC 4

clock September 11, 2012 07:31 by author Scott

In this blog post I will show how to implement a custom XmlMediaTypeFormatter that extends the default ASP.NET Web API XmlMediaTypeFormatter in a way that it ignores XML namespaces when parsing xml messages.

By default the ASP.NET Web API
XmlMediaTypeFormatter is not able to parse XML requests that contain any XML namespace declarations. If you would like to support clients, that (for any reason) send messages containing XML namespaces you can use the IgnoreNamespacesXmlMediaTypeFormatter that is defined as follows:

public
class IgnoreNamespacesXmlMediaTypeFormatter : XmlMediaTypeFormatter
{

  // See http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
  private const string NamespaceRemover =
    @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
        <xsl:output method='xml' indent='no'/>
        <xsl:template match='/|comment()|processing-instruction()'>
          <xsl:copy>
            <xsl:apply-templates/>
          </xsl:copy>
        </xsl:template>
        <xsl:template match='*'>
          <xsl:element name='{local-name()}'>
            <xsl:apply-templates select='@*|node()'/>
          </xsl:element>
        </xsl:template>
        <xsl:template match='@*'>
          <xsl:attribute name='{local-name()}'>
            <xsl:value-of select='.'/>
          </xsl:attribute>
        </xsl:template>
      </xsl:stylesheet>";

  private readonly XslCompiledTransform _xlstTransformer;

  public IgnoreNamespacesXmlMediaTypeFormatter()
  {
    var xslt = XDocument.Parse(NamespaceRemover, LoadOptions.PreserveWhitespace);
    _xlstTransformer = new XslCompiledTransform();
    _xlstTransformer.Load(xslt.CreateReader(), new XsltSettings(), new XmlUrlResolver());
  }

  public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
  {
    try
    {
      // Read XML
      var xmlDocument = XDocument.Load(new XmlTextReader(stream));

      // Transform XML
      var resultStream = new MemoryStream();
      _xlstTransformer.Transform(xmlDocument.CreateReader(), XmlWriter.Create(resultStream, new XmlWriterSettings() { OmitXmlDeclaration = true }));
      resultStream.Position = 0;

      // Process request with XmlMediaTypeFormatter default functionality
      return base.ReadFromStreamAsync(type, resultStream, contentHeaders, formatterLogger);
    }
    catch (XmlException)
    {
      return base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
    }
  }
}


In detail the
IgnoreNamespacesXmlMediaTypeFormatter removes the XML namespace declarations from the XML message and passes the modified XML to the base class to use the default XmlMediaTypeFormatter functionality. Removing the XML namespaces is done with a XSLT transformation (see http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl).

To activate the
IgnoreNamespacesXmlMediaTypeFormatter add the following lines in the file Global.asax.cs:

protected
void Application_Start()
{

  [...]
  // Remove default XmlFormatter and add (customized) IgnoreNamespacesXmlMediaTypeFormatter

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

  var ignoreNamespacesXmlMediaTypeFormatter = new IgnoreNamespacesXmlMediaTypeFormatter{ UseXmlSerializer = true };

GlobalConfiguration.Configuration.Formatters.Add(ignoreNamespacesXmlMediaTypeFormatter);

  [...]
}

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Heads up on a hidden breaking change in ASP.NET MVC 4

clock August 24, 2012 07:51 by author Scott

If you use an Editor Template for DateTime and use the DataTypeAttribute with either or DataType.Date and DataType.DateTime in ASP.NET MVC 2 or 3 and happen to upgrade to ASP.NET MVC 4 be aware!

ASP.NET MVC 4 introduces two new internal editor templates for properties marked as DataType.Date and DataType.DateTime to render HTML5 input types (date and datetime accordingly).

The unexpected side-effect of this is that if you were previously capturing all DateTime type editing through a DateTime editor template now if your property is marked as DataType.Date ASP.NET MVC 4 will use the new internal Date editor template instead of your DateTime editor template.

The solution is to provide a Date.cshtml editor template along your DateTime.cshtml editor template.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Create Separate Web API’s Action for Mobile Request: ASP.NET MVC 4

clock June 19, 2012 07:11 by author Scott

ASP.NET MVC 4.0 has two great features: One is Display Mode allows you to create mobile-specific and desktop-specific views and Second is Web API platform for building RESTful applications. Sometimes, You might need to return different data or perform different operations for desktop and mobile request. This article explains how to implement separate actions for mobile request keeping same URL format in Web API.

1. In Visual Studio, Select File > New Project > ASP.NET MVC 4 Web Application > Enter name > OK


2. Select ‘Web API‘ > View Engine: ‘Razor‘ > OK


3. You’ll get default ValuesController. When you access <your app url>/api/Values, the array of string value1, value2 is returned.


To create separate action for mobile request, We are going to create separate controller having ‘Mobile‘ suffix.


Right Click on ‘Controllers‘ folder > Add Controller > Give Name ‘ValuesMobileController‘ > Template: ‘API Controller with empty read/write actions‘ > Add


To differentiate both controllers, replace value1, value2 to mobile-value1, mobile-value2 in get method.


4. Now our object is to call action of Mobile controller when request comes from mobile device.


In Global.asax:


default api route:


routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );

Change it to


routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           ).RouteHandler = new MyRouteHandler();

and add following class:


public class MyRouteHandler : HttpControllerRouteHandler
   {
       protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
       {
           //Check whether request comes from mobile browser
           if (requestContext.HttpContext.Request.Browser.IsMobileDevice)
           {
               string controller = requestContext.RouteData.Values["controller"].ToString();
               requestContext.RouteData.Values["controller"] = controller + "Mobile";
           }
           return new MyHttpControllerHandler(requestContext.RouteData);
       }
   }

   public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
   {
       public MyHttpControllerHandler(RouteData routeData)
           : base(routeData)
       {
       }
   }

You have to import following namespaces:


using System.Web.Http.WebHost;
using System.Web.SessionState;

In this RouteHandler, Request.Browser.IsMobileDevice checks whether request comes from mobile browser and change controller name with ‘Mobile‘ suffix.

Now run app on browser, For testing, You can change user-agent to iPhone with user agent switcher Firefox add-on and open same URL. you’ll get mobile-value1 and mobile-value2.



Hope it helps

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 2

clock June 4, 2012 08:29 by author Scott

Please see the previous post at here.

Once I removed all the TasksController files and the TodoItem, I chose the Models folder, right click and “Add New Item” and searched for “ADO.NET Entity Model” and added it to the folder.




It allowed me to connect to the Northwind database through “Generate from database” and I selected just three tables “Products”, “Categories” and “Suppliers” table for simplicity. At the end of the wizard, we get a EDMX design file with the 3 tables. On this screen I right clicked and choose “Add Code Generation Item” as below




and then in the dialog that came up, chose the “ADO.NET DbContext Generator” and Added (note, if you don’t see this template, you probably don’t have
Entity Framework 4.1 installed)

This step created the Model1.Context (not required for us though) and the Model1.tt template which groups the individual class files for each of the tables above (these are required)


The next thing I did, was to remove the NorthwindEntities connectionstring that got automatically added when we followed the ADO.NET Entity Model wizard. We don’t need this connection string.


Also, I deleted the Model1.Context file and also the Model1.cs files which are not required (we will be generating a new context to suit our database name)




Note that these files are not required only for our SPA approach here and they are required when working with EF CodeFirst normally as they do the DbSet Tracking and whole bunch of things


So, we now have the basic model classes required for wiring up our Controller required to create the SPA Pages. One important thing I learnt in this process was that, I had to edit the Model classes as follows:-


In Supplier.cs added the “private” keyword to the ICollection<Products> property. Same is the case with Category.cs. Otherwise you would run into an
error explained here.



After this, I added Controller for Products as per the settings below (Right Click Controller – Add –Controller)




Note several important things. I have chosen the “Single Page Application with read/write actions and views, using Entity Framework” template under Scaffolding options. Also, I have edited the Data context class and made it simply MvcApplication126.Models.Northwind. This would be referenced in the web.config connection string as well so that SPA picks up our existing Northwind database instead of creating a new one.


Once you click “Add” the following files are generated.


Under Controllers


- NorthwindController.cs

- NorthwindController.Product.cs
- ProductsController.cs

Under Scripts


- ProductsviewModel.js


Under Views


- Products folder and the Views and Partial Views required


Repeat the steps for adding Controllers for “Categories” and “Suppliers” and the only change would be the respective Model Classes.


One important thing to do is to add the following connectionstring to the web.config file


<add name="Northwind" connectionString="Data Source=SERVERNAME;Initial Catalog=Northwind;User Id=YOUR USER NAME;Password=YOUR PASSWORD" providerName="System.Data.SqlClient" />


Then, when you run the project, it opens up the default Home Page.


- Navigate to /Products and it should load the list of Products from Northwind database.

- Click on each product and edit and note that everything happens in a single page inline.
- Just notice the URLs change in pattern with hash tags.
- Notice that the Categories and Suppliers are wired up as dropdownlists since these are foreign key references.
- Notice that all the items load asynchronously

I went ahead and edited the Shared –> Layout.cshtml under Views folder to add Menu Items for Products, Categories and Suppliers, as below:-


<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Products", "Index", "Products")</li>
<li>@Html.ActionLink("Categories", "Index", "Categories")</li>
<li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>


Now, we have our full blown Northwind Traders Application running as a SPA.


You can download the sample from
https://skydrive.live.com/redir.aspx?cid=069f94a102eff49a&resid=69F94A102EFF49A!919&parid=root

 

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 1

clock May 30, 2012 06:42 by author Scott

Single Page Application Frameworks are gaining popularity in the ever evolving web community with lot of libraries such as JavaScriptMVC, Backbonejs and many other libraries. ASP.NET MVC 4 introduces experimental support for building single page application (SPA) through a template. Much of the plumbing work of wiring up the client side scripts, javascript modelviews and the controllers is automated, making it a quick start to develop SPAs relatively easier. Lets examine a scenario where we are building a Northwind Store using SPA.

I installed the
ASP.NET MVC 4 Beta for Visual Studio 2010 and the Northwind Sample Database for SQL Server

Post that I did a “File – New Project – ASP.NET MVC 4 Web Application”




In MVC 3 we are used to see a screen with 3 options i.e. Intranet, Internet and Empty templates. In MVC 4 we have additional templates as you can see below and I chose the “Single Page Application” template and created the project template.




In MVC 3 we are used to see a screen with 3 options i.e. Intranet, Internet and Empty templates. In MVC 4 we have additional templates as you can see below and I chose the “Single Page Application” template and created the project template.




Next, the important folder is the Scripts folder and there I found that it creates a <Modelname>ViewModel.js file that holds all the observer pattern script required. In addition, this folder contains a truckload of JavaScript files including jQuery, Knockout, upshot and modernizr.




Finally, inside the “Views” folder, it creates the necessary Partial Views and Index View for Tasks. Once you build and run, you can experience all of this SPA for your TodoItem Model without having written a single line of JavaScript code yet.


So, you learn


1. The ContextName that you select when creating the TasksConroller (inour case it is MVCApplication126Context)is important for you to work with other Databases. By default when you run this solution, Visual Studio would create a SQL Express Database in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA folder with the name MVCApplication126Context.

The way I see the SPA framework identifies is, if you don’t have a connectionstring by the name of the Context, it defaults to creating a database in SQL Express with the ContextName in the above mentioned path.

If you have a connectionstring mentioned with the same contextname, it tries and uses that Database (SQL Express, SQL Server). However, when you are running for the first time, if you create a Database and point it in the connectionstring, it would expect that the Table (mapped to the model i.e. TodoItems) need to exist. Otherwise, it throws an exception. So best, is to either use a Model for which there is a Table that already exists in the Database or provide a new Database name in which case, VS would create the Database with the TodoItems Table as well. There must be someplace to configure all of these, but for the lack of time I didn’t delve deep into these things for now.


So, coming to our Northwind Sample. Northwind has been Developers’ best friend to experiment new things and the saga continues here.


I had to do a couple of things though. First I removed the TodoItem.cs class and also removed the TasksController, Views since we don’t need them. So, for all practical purposes, it is now a plain MVC 4 Application with the default Home & Account Controllers and their respective Views. I also removed the Contextfiles created inside the Controllers Folder.


A bit of analogy on how I built this Northwind App before I explain the actual steps.


The TodoItem is a simple class file and can be hand wired. However, in real world, or for that matter, a simple Northwind database table has a lot of columns and hence properties to be wired up. Also, it requires to map foreign relationships and other things. So, I decided to use the ADO.NET Entity Data Model first to create a model class for the Northwind Database. This would help me in generating DbContext classes using EF CodeFirst Template, which are much simpler than the complex EDMX file that is created by the ADO.NET Entity Model. Thereafter, I can use the class files generated to create the Controller, View and JS ViewModels.

 

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Display Mode in ASP.NET MVC 4

clock April 6, 2012 05:09 by author Scott

This is the second article focusing on the new additions to ASP.NET MVC 4. Today’s article will focus on using Display Modes. This selects a view depending on the browser making the request, which means you can target specific devices and give the user a truly rich experience.

Before getting started, you should read the
first article in this series on ASP.NET MVC 4 Developer Preview.

Installation

Before undertaking any development, you’ll need to install the MVC 4 builds. The simplest way to do this is via the Web Platform Installer. MVC 4 is available for Visual Studio 2010 or Visual Studio 2011 Developer Preview.


All of the MVC articles I’m authoring are developed in Visual Studio 2011 Developer Preview. Below are the links to get started.

-
ASP.NET MVC 4 for Visual Studio 2010
-
ASP.NET MVC 4 for Visual Studio 2011 Developer Preview

Default Mobile Views in MVC 4

It’s important to understand a new feature in MVC 4. By default, if you add a .mobile.cshtml view to a folder, that view will be rendered by mobile and tablet devices.



This is a nice feature, but if you want to target specific devices, such as the iPhone, iPad or Windows Phone, you can use
Display Modes.

To do this, you need to register a new
DefaultDisplayMode instance to specify which name to search for when a request meets the condition. You set this in the global.asax file in the Application_Start event. Here’s how to specify a display mode for an iPhone.

protected void Application_Start()

{

DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")

{

ContextCondition = (context =>context.Request.UserAgent.IndexOf

("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)

});

}


To consume views that meet this condition, you create a view but change the extension to
.iPhone.cshtml. Likewise if you want to target an iPad, create an iPad instance.

DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPad")

{

ContextCondition = (context =>context.Request.UserAgent.IndexOf

("iPad", StringComparison.OrdinalIgnoreCase) >= 0)

});

Basically,
Display Modes checks the User Agent. If it finds a matching suffix, it will display any view it finds that matches the suffix. The suffix is the parameter that’s passed to the DefaultDisplayMode method. To see this in action, I’ve created a Home controller and added three views to the Home folder.



The differences between the views is the H1 heading. They’ll display
iPhone, iPad or Desktop depending on the device. I’m also displaying the User Agent so you can see it changing. First I’ll debug the website through my desktop browser. You can see the desktop specific page being served.



Now navigate to the website using an iPhone. You’ll see the iPhone specific page being served.




Switching over to an iPad, you’ll see the iPad specific page being served.




This is a simple way to target specific devices, producing a view that suits the device – and thus the user.


Testing with Emulators


To test these new features, you can either use a physical iPhone or iPad, or you can use an emulator. The emulator I was using is from MobiOne. You can download a 15 day free trial
here.

The Windows Phone RC emulator is free and can be downloaded
here.

Likewise another good option is the User Agent Switcher add-on for Firefox, which changes the user agent that’s sent to the browser. That can be downloaded
here.

Do you want to test new ASP.NET MVC 4 hosting for
FREE??? Please visit our site at http://www.hostforlife.eu/ASPNET-45-Beta-European-Hosting.aspx.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in