Archive for September, 2008

Model-based validation for ASP.NET MVC: better approach

No Comments » | Tuesday, September 9th, 2008

In my previous post about model-based validation I introduced my concept of validating data using attributes as well as using my own HTML helpers to display errors. Many things have changed since then because of new MVC release. What’s new in ASP.NET MVC Preview 5?

  • ModelState class which stores model’s validation errors and
  • Model binders for populating data from forms to strongly typed objects.

You can read more about it in Scott gu’s article ASP.NET MVC Preview 5 and Form Posting Scenarios.

That’s why I have updated my code from last time to use some new stuff and to get much shorter code in controllers:

[ActionName("Create"), AcceptVerbs("POST")]
public ActionResult Save()
{
    if (this.IsModelValid(typeof(TestModel)))
    {
        // Save it, just an example
        _repository.Save<TestModel>(ViewData.Model);

        return RedirectToAction("Done");
    }

    return View("Index");
}

What IsModelValid() does?

  • validates submitted data (according to type, name and attributes)
  • populates ViewData.ModelState with errors
  • populates ViewData.Model

I really like this idea (code is very readable) but after reading Thoughts on validation in ASP.NET MVC applications I realized that my approach lacks in some ways:

  • no repository specific error handling
  • violating some good principles

So althrought Steve Sanderson’s code is a bit longer, his validation concept make sense and I am really looking forward to see it in action!

Are you getting errors after installing ASP.NET MVC Preview 5 for no reason?

No Comments » | Sunday, September 7th, 2008

Well I was. I uninstalled previous version, installed new one, created a blank new MVC project and got following errors:

Could not load type 'System.Web.Routing.StopRoutingHandler' from assembly 'System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

The UrlRoutingHandler is not used to directly handle requests.

If you are in the same situation I have good news for you! I solved it just by installing VS & .NET 3.5 Service Pack 1! You can get it here. I hope this helps you too!

Hostgator is going to host .NET sites in the nearly future