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 3 Hosting :: ASP.NET MVC3 Tools Update – Scaffolding with the Repository Pattern

clock July 8, 2011 08:28 by author Scott

In this post I’m going to show you how to use MvcScaffolding to add a new controller template to enable scaffolding with data access code that uses the Repository Pattern.

One of the new features is built in tooling support for scaffolding. The “Add Controller” Dialog box has been revamped to include a few new options.

As you can see there are much more options as compared to before. The scaffolding options are as follows:

- Template: Allow you to specificy what kind of controller you want to generate. Out of the box you get an empty controller (Just a class with no actions), Controller with actions and views using the Entity Framework code first, and controller with empty read/write actions.

- Model: This is the object that will be used for scaffolding strongly typed views, CRUD actions and data access.

- DataContext: By default this is an EF Code First class that inherits from DbContext. You can either select an existing context or have the scaffolding tools create a new one for you.

- Views: Select between ASPX and Razor. This is pretty much the same as the “Add New View” dialog box.

- Advanced Options include layout/master page settings and View script settings. Again, stuff that is also in the “Add New View” Dialog.



Scaffolding using the “Controller with read/write actions and views, using Entity Framework” is especially cool because it generates a controller, all associated views AND data access code for you. That’s right, all you need to do is create an model class and the scaffolder does the rest. How’s that for a productivity boost?


To test this I created a simple Product class which is defined as the following:

public class Product{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}


Then I added a new controller with the following options:



The new tooling support created a new controller, all associated views and the data access code. That’s really cool, but let’s take a look at the controller code.

private ProductContext db = new ProductContext();
 //
// GET: /Product/
 public ViewResult Index()
{
return View(db.Products.ToList());
}


By default the scaffolding tools use the ProductContext object directly in the Controller. Many people don’t like this coupling (myself included) and prefer to use
the Repository Pattern. This allows us to abstract away our data access code behind a repository, making it easier to work with and later modify, if need be.

Well the good news is that the add controller dialog is extensible. You can add your own controller templates to enable data access using any technology mechanism you want.

I’m going to show you a way to get a repository option for EntityFramework to show up with very little work. All you need to do is install the MvcScaffolding NuGet Package.

Open the Package Manager Console and enter “Install-Package MvcScaffolding”:



Now right click on the controllers folder and select “Add”->”Controller”. We’re going to re-scaffold out our ProductController, associated views and data access code (WARNING: This will overwrite any changes you have made so be careful.)

Now take a look at the templates section and you should see new templates:



The last option let’s you scaffold out the entire thing and use repositories for data access. Go ahead and click “Add”. Check the checkboxes to allow the scaffolder to override existing items.

We can verify this by looking at our ProductController and we should see the following:

private readonly IProductRepository productRepository;

// If you are using Dependency Injection, you can delete the following constructor
public ProductController() : this(new ProductRepository()) { }
 public ProductController(IProductRepository productRepository) {
this.productRepository = productRepository;
}

//
// GET: /Product/
 public ViewResult Index(){
return View(productRepository.All);
}

Now the controller uses a repository instead of hard coding in the data access code. The repository itself uses EF Code First to do all the data access.



European ASP.NET MVC Hosting :: ASP.NET MVC Routing Tutorial

clock July 7, 2011 07:23 by author Scott

In this tutorial, you are introduced to an important feature of every ASP.NET MVC application called ASP.NET Routing. The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. By the end of this tutorial, you will understand how the standard route table maps requests to controller actions.

Using the Default Route Table

When you create a new ASP.NET MVC application, the application is already configured to use ASP.NET Routing. ASP.NET Routing is setup in two places.

First, ASP.NET Routing is enabled in your application's Web configuration file (Web.config file). There are four sections in the configuration file that are relevant to routing: the system.web.httpModules section, the system.web.httpHandlers section, the system.webserver.modules section, and the system.webserver.handlers section. Be careful not to delete these sections because without these sections routing will no longer work.

Second, and more importantly, a route table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event.

The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.

Listing 1 - Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.

Imagine that you enter the following URL into your web browser's address bar:

/Home/Index/3

The Default route maps this URL to the following parameters:

controller = Home

action = Index

id = 3

When you request the URL /Home/Index/3, the following code is executed:

HomeController.Index(3)

The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Home. If you don't supply an action, the action parameter defaults to the value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.

Let's look at a few examples of how the Default route maps URLs to controller actions. Imagine that you enter the following URL into your browser address bar:

/Home

Because of the Default route parameter defaults, entering this URL will cause the Index() method of the HomeController class in Listing 2 to be called.

Listing 2 - HomeController.cs

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(string id)
        {
            return View();
        }
    }
}

In Listing 2, the HomeController class includes a method named Index() that accepts a single parameter named Id. The URL /Home causes the Index() method to be called with an empty string as the value of the Id parameter.

Because of the way that the MVC framework invokes controller actions, the URL /Home also matches the Index() method of the HomeController class in Listing 3.

Listing 3 - HomeController.cs (Index action with no parameter)

using System.Web.Mvc;


namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

The Index() method in Listing 3 does not accept any parameters. The URL /Home will cause this Index() method to be called. The URL /Home/Index/3 also invokes this method (the Id is ignored).

The URL /Home also matches the Index() method of the HomeController class in Listing 4.

Listing 4 - HomeController.cs (Index action with nullable parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            return View();
        }
    }
}

In Listing 4, the Index() method has one Integer parameter. Because the parameter is a nullable parameter (can have the value Null), the Index() can be called without raising an error.

Finally, invoking the Index() method in Listing 5 with the URL /Home causes an exception since the Id parameter is not a nullable parameter. If you attempt to invoke the Index() method then you get the error displayed in Figure 1.

Listing 5 - HomeController.cs (Index action with Id parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int id)
        {
            return View();
        }
    }
}



The URL /Home/Index/3, on the other hand, works just fine with the Index controller action in Listing 5. The request /Home/Index/3 causes the Index() method to be called with an Id parameter that has the value 3.

Summary

The goal of this tutorial was to provide you with a brief introduction to ASP.NET Routing. We examined the default route table that you get with a new ASP.NET MVC application. You learned how the default route maps URLs to controller actions. Hope the tutorial can help and give benefit for all of you.



European ASP.NET MVC 3 Hosting :: Remote Validation in ASP.NET MVC 3 RC1

clock June 22, 2011 06:35 by author Scott

Remote validation has finally landed in RC1 of ASP.NET MVC 3.  It’s a weird area as more often than not people tend to over complicate something that is really pretty simple.  Thankfully the MVC implementation is fairly straightforward by simply providing wiring allowing the jQuery Validation plugin to work it's magic.  Basically there is a new Remote attribute that can be used like so.

public class Credentials
{   
    [Remote("Username", "Validation")]
    public string Username { get; set; }    

    public string Password { get; set; }
}

As you can see we have attributed the Username field with a Remote attribute.  The 2 parameters tell us what Action and Controller we should call to perform the validation.  This does make me feel slightly uneasy as it kind of feels like you are coupling the controller to the model which doesn't sit right by me.  currently sitting on the fence I'll see how it works in real life.  Anyway I implemented it like so,

public class ValidationController : Controller
{    public ActionResult Username(string UserName)
    {
        return Json(Repository.UserExists(Username), JsonRequestBehavior.AllowGet);
    }
}

And thats you - provided you have the necessary client side libraries included of course (jQuery, jQuery Validate etc). and have Client Side Validation turned on (now by default in MVC3).


Configuration

The Remote attribute offers a few nice little configuration options to make things easier.  The typical ones are there such as ErrorMessage, ErrorResource etc. but there are a few specific ones as well.

Fields

There may be a case where ding the name and the value of a single form field isn’t enough to perform validation.  Perhaps validation is affected by some other field/value in the form.  The Remote attribute accepts a comma separated list of other fields that need to be sent up with the request using the Fields parameter

This basic example will send up the value of the EmailService input field along with the value of Username.  Clean and simple.

[Remote("Username", "Validation", Fields = "EmailService")]

HttpMethod

HttpMethod simply allows us to change how the ajax request is sent e.g. via POST or GET or anything else that makes sense.  So to send a remote request via POST

[Remote("Username", "Validation", HttpMethod = "POST")]

A Minor Difference

You might notice if you read the release notes for RC1 that my implementation of the controller is slightly different.  The reason being that the example in the release notes is broken :-).  The example looks like this

public class UsersController {
    public bool UserNameAvailable(string username) {
        return !MyRepository.UserNameExists(username);
    }
}

However the Validate plugin expects a JSON response which is fine on the surface but returning a boolean response to the client side results in a response body of False (notice the captial F) which in turn causes a parse error when the plugin performs JSON.parse.  My suggested solution is actually more inline with how most people would typically write an Ajax capable controller action anyway (though I am not happy with the JsonRequestBehaviour usage) but there are other ways but they aren’t pretty….

public class ValidationController : Controller
{       
    public string Username(string username)
    {
        return (!Repository.UserExists(Username)).ToString().ToLower();
    }
}

See?  Ugly and plain WRONG (but it will work).

Nice to see this feature finally landing as it can be useful in certain situations.



European ASP.NET MVC 3 Hosting :: Error 0x80070643 When Install ASP.NET MVC 3, How to Fix It?

clock June 9, 2011 05:00 by author Scott

Have you ever get this error message when you installed your ASP.NET MVC 3?



This is the steps that I took to fix it:

1. Remove the trailing backslash from the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0\Path

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\4.0.30319.0\Path

2. Uninstalled the old version of "Microsoft ASP.NET Web Pages".

3. Add the trailing backslash back to those keys.

4. Install MVC 3.



Good luck!!



European ASP.NET MVC 3 Hosting :: Get Selected Row from ASP.NET MVC 3 WebGrid

clock June 2, 2011 06:00 by author Scott

Every website has to display data and every website has a Grid control. In ASP.NET MVC 3 there’s the WebGrid, which is part of the Microsoft Web Helpers library. This can be downloaded through NuGet (formerly NuPack). NuGet is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. One piece of functionality that is critical is reacting when the user selects an item in the WebGrid. This article will focus on finding out which row was selected, but also how to find out more about the data that is selected.

Before moving on, you need to download ASP.NET MVC 3.
Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. To focus on the answer, I’ve got a simple model as seen below.



Using the WebGrid, it’s easy to display this data to the user.



The first column is the key to making this work. @item.GetSelectLink outputs a HTML anchor tag with the row selected. This is passed as a
QueryString, and the name of the QueryString is set by the selectionFieldName property set on the grid.



To find out what row is selected is just as easy. The WebGrid has a property called
SelectedRow. This sets a reference to a GridViewRow object that represents the selected row in the control. When you combine this with the HasSelection property, you can get the selected row like this.



I’ve created a partial view called _Person.cshtml. The file begins with an underscore (_) because I don’t want this file called directly from the web. The second parameter is the data being passed into the partial view. The data in this instance is the selected row.



Very easy, right??



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