Posts Tagged ‘MVC’

Automatic control in ASP.NET MVC

Thursday, September 2nd, 2010

Although the convention proposed by the ASP.NET MVC framework help us to structure our applications and, in most cases, be more productive, occasionally also require us to enter repetitive code to comply with the proposed standard.

For example, in the case of controllers with actions that return the default view, we usually use a code like the following:

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

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

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

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

}

It’s not terrible, but drivers with many actions of this type can be a bit heavy … can not we do something to improve this?
Automatic controllers

Looking at the driver code above, we see that the execution logic is very simple: every action returns the user implemented view as rightful convention. Obviously this is a widespread behavior may be playing with the extension mechanisms of the framework.

A very quick way to do it is to overwrite the method HandleUnknownAction() class Controller , described here some time ago , which allows us to process the requests made to non-existent shares in the controller.

Remember that when a request comes to a controller, running the method whose name matches the action invoked, in the absence of the framework call HandleUnknownAction() , allowing us to take control of the situation. In our case, we could introduce the logic in this method to return the user, automatically, a view whose name matches the action, following the standard naming convention.

To do this, simply create a base class called AutoController , and enter the following code to have the problem solved:

public class AutoController : Controller
{
    protected override void HandleUnknownAction(string strActionName)
    {
 
        //  Try to find a view with the name of the action ...
 
        ViewEngineResult viewResult = ViewEngines.Engines.FindView
                            (this.ControllerContext, , null) ;
 
        if (viewResult.View != null)
        {
            View(strActionName).ExecuteResult(ControllerContext);
            return;
        }
 
        // If we have not found anything, we follow the
        // Default behavior ...
 
        base.HandleUnknownAction(strActionName);
    }

Simple, no? All we do in the code is to use the library ViewEngines to seek a view whose name matches the action you are trying to run, returning it to the user if possible locate it.

If you can not find a view for the action invoked, will run the default treatment for this situation, which is nothing more than throwing an exception of type HttpException with error 404 (not found).

That’s it! From this point, all the driver classes that inherit from AutoController include this behavior, so it will be possible to avoid the implementation of methods whose sole mission is to return the default view as convention.

For example, the driver that we wrote at the beginning of this post might be as follows, much more compact:

public class HomeController: AutoController
{
}

But beware if that is not gold that glitters …

However, before using this technique we must be clear what it really means to not run into unpleasant surprises.

Each request received by the controller is not explicitly implemented will be processed with the operator introduced in HandleUnknowAction() without passing through any type of filter, or send any information in the ViewData .

For example, it would be possible to access the view directly, only know her name, which in some scenarios may be dangerous from the point of view of system security.

Obviously, the technique is also not valid at times when the sight expect to receive some form of driver information (like data view, or indication of use of a specific master page), or when the action must be decorated with a filter .

In these cases, these concrete actions should continue to be implemented explicitly in the controller, but the rest can continue to be processed automatically:

public class HomeController: AutoController
{
    // GET /Home/Employers
    //  Only for registered users
    [Authorize]
    public ActionResult Employers()
    {
        return View();
    }
 
    // GET /Home/Salary
    public ActionResult Salary()
    {
        var varAppServices = new AppServices();
        return View(varAppServices.GetReferences());
    }
 
    // GET /Home/{ExamplePage}
    // Default processing, returns the view {ExamplePage}
}

In summary, in this post we have studied a technique that allows us to create drivers capable of providing a default for all requests made to the same, saving the writing of actions that simply return the default view.

And although, like everything else, practice has limitations and dangers, its use can be interesting websites without major safety requirements, such as public information websites, whose drivers are mostly of the type described.

Processing requests for actions not available in ASP.NET MVC

Sunday, August 22nd, 2010

ASP.NET MVC controllers that inherit from the Controller can easily process the requests made to actions not defined. To do this, all you have to do is override the method HandleUnknownAction() and implement the logic that we want to run in these cases.

In the following code, the requests made to /Home/Index and /Home/About will be processed normally, but /Home/ActionPage will be processed by HandleUnknownAction , whose implementation will show the view “Index” with a personalized message:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
protected override void HandleUnknownAction(string strActionName)
(
ViewData ["Message"] = "Are you trying to" + strActionName + "?"
View("Index").ExecuteResult(this.ControllerContext);
)
)

Happy Programming!! ;-)

Collection of free chapters of books on ASP.NET MVC

Monday, September 7th, 2009

I received some messages from readers Wisecodes who want to begin in ASP.NET MVC, but do not know where to start, and I suggest you write some posts that explain this new framework from scratch. Perhaps someday it, but meanwhile, I reminded them that there are free resources that can be very useful to take the first steps (and even dig a little) on this technology.

For example, recently have appeared a large number of books on ASP.NET MVC, and most of them can download free chapters, in addition to help us decide which of them might be in our interest to have the information value we can provide. Like always, the issue is the spread of this information, so I decided to make this compilation to have them all by hand. As you’ll discover new pieces expand the list, and of course, if you know someone who is not here, I’ll comment’s and add it.

That yes, all in English, to be very technical but I think they are easy to understand.

Pro ASP.NET MVC Framework Pro ASP.NET MVC Framework
Author: Steve Sanderson
Post-show: Now Published Pro ASP.NET MVC Framework (Apress) «Steve Sanderson’s blog
Free Chapter: Chapter 2: Your First ASP.NET MVC Application (23 pages) In this chapter, the author shows in great detail, almost step by step, how to create our first simple application with ASP.NET MVC. First, it creates a very basic project through which explains the basics of programming by following this model, and then goes into the creation of a mini-application data entry, validations and simple logic.
Professional ASP.NET 1.0 MVC Professional ASP.NET 1.0 MVC
Authors: Scott Hanselman Rob Conery, Phil Haack and Scott GuthrieFree

Chapter: Chapter 1: Nerdinner (192 pages)
This extensive chapter describes the creation of a moderately complex site, www.nerddinner.com, using large amounts of related technologies such as filters MVC framework, Ajax, LinqToSql, unit testing, etc.. Highly recommended, essential.

ASP.NET MVC 1.0 Quickly ASP.NET MVC 1.0 Quickly
Author: Maarten Balliauw
Post-show: Announcing my book, ASP.NET MVC 1.0 Quickly
Free Chapter: Chapter 2: Your first ASP.NET MVC application (20 pages)
A brief tour of the process of creating an MVC application, the system routes, controllers, views, and unit testing. Pretty basic, perhaps too “quickly”, but valid in any case.
PASP.NET MVC in Action ASP.NET MVC in Action
Authors: Jeffrey Palermo, Ben Scheirman, Jimmy Bogard
Post-show: Announcing ASP.NET MVC in Action (from Manning) – Jeffrey Palermo (. Com) – CodeBetter.Com
Free resource: Getting Started with the ASP.NET MVC Framework (Green Paper – PDF) (18 pages) (The link to the document you sent by email after submitting your address.) This is another introduction to the framework, the system routes, controllers and views from scratch.Free Chapter: Chapter 9: AJAX in ASP.NET MVC (21 pages)
Interesting introductory chapter to the use of Ajax technology on ASP.NET MVC using jQuery and Ajax helpers to exchange data with the server.
ASP.NET MVC Framework Unleashed ASP.NET MVC Framework Unleashed
Author: Stephen Walther
Free chapters: the author has published several chapters in his blog, and withdraw as soon as the book is available at Amazon, so hurry up that the contents are excellent.
Chapter 1 – An Introduction to ASP.NET MVC
Chapter 2 – Building a Simple ASP.NET MVC Application
Chapter 3 – Understanding Controllers
Chapter 4 – Understanding Views
Chapter 5 – Understanding Models
Chapter 6 – Understanding HTML Helpers
Chapter 9 – Understanding Routing
Beginning ASP.NET MVC 1.0 Beginning ASP.NET MVC 1.0
Authors: Simone Chiaretto, Keyvan Nayyeri
Free Chapter: Chapter 9: Testing ASP.NET MVC Applications (38 pages)
Interesting chapter describes various techniques for unit testing of applications built with this framework, including the creation of mocks, dependency injection controllers, testing route and obliquely, some TDD.

Free eBooks For Beginner Programmers

Wednesday, March 11th, 2009

1) ASP.NET MVC

A strong 195 pages with chapters of Wiley Publishing published book “Professional ASP.NET 1.0 MVC” is a preliminary version in PDF format. The book was written by renowned authors Rob Conery, Scott Hanselman, Phil Haack and Scott Guthrie.

The free chapter gives a detailed example of the project NerdDinner, a website to plan and arrange joint dinner. It is shown how this small but complete application built with ASP.NET MVC. The source code can be found on Codeplex (http://nerddinner.codeplex.com) .

Click here to download.

2) Microsoft Visual Studio 2008 EBooks (LINQ, Silverlight 2 and ASP NET 3.5)

Microsoft hass published interesting three books. Great!

  1. Introducing Microsoft LINQ
  2. Introducing Microsoft ASP.NET AJAX
  3. Introducing Microsoft Silverlight 1.0

Click here to download.

3) Understanding Microsoft Virtualization Solutions

Microsoft Press has published “Understanding Microsoft Virtualization Solutions – From the Desktop to the Datacenter” now available as free downloads. Great! ! Microsoft seems to have missed the virtualization pattern gradually came to really try.

Click here to download.

4) 7 Development Projects for Microsoft Office Sharepoint Server 2007 and Windows Sharepoint Services Version 3.0

Click here to download.

ASP.NET MVC 1.0 Release Candidate Now Available

Friday, February 20th, 2009

Today we shipped the ASP.NET MVC 1.0 Release Candidate (RC).  Click here to download it (note: the link just went live so if it isn’t working wait a few minutes for the server you are hitting to refresh).  It works with both Visual Studio 2008 and Visual Web Developer 2008 (which is free).

Today’s RC is the last public release of ASP.NET MVC that we’ll ship prior to the final “1.0” release.  We expect to ship the final ASP.NET MVC 1.0 release next month.

In addition to bug fixes, today’s build includes several new features.  It also includes some refinements to existing features based on customer feedback.  Please read the release notes that ship with the ASP.NET MVC download for full details on all changes.  The release notes include detailed instructions on how to upgrade existing applications built with the ASP.NET MVC Beta to the RC.

Read More..