Posts in "ASP.NET MVC" tag

Import Namespaces for Razor Views

Posted on 28 July 2010 and tagged with , 0 comments

Previously when developing with the WebForms view engine we could use the Web.config file to import namespaces where we stored our extension methods or models. They would then be available to all our views without having to explicitly declare them in each view.

In Razor this is no longer possible due to how it’s built, which is why we have to manually register them in the Application_Start event.

To do this begin with opening Global.asax and create a new method called RegisterGlobalImports, and call it from the Application_Start method. In the newly created method you add all the namespaces you wish to have in your view by calling AddGlobalImport on CodeGeneratorSettings.

public static void RegisterGlobalImports() {
    CodeGeneratorSettings.AddGlobalImport("MvcApplicationRazor.Core.Extensions");
    CodeGeneratorSettings.AddGlobalImport("MvcApplicationRazor.Core.Models");
}

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

I usually register extension methods, that should be available in the view, and models so I won’t have to type namespaces over and over again.

Read More »

Getting HTML Colorization with Razor View Engine

Posted on 27 July 2010 and tagged with , , 0 comments

imageToday the Gu announced the first preview of ASP.NET MVC 3, which included the new Razor view engine. I’ve been really excited about it as I feel it makes our views a lot prettier than before with Web Forms view engine. It will also be a lot quicker and smoother to type without all those messy <%-characters.

To the point! I am currently upgrading an existing site to use MVC 3 and Razor. However in this first preview of MVC 3 we won’t have any File Colorization or IntelliSense in .cshtml files. This means it will look like we’re editing in Notepad. It got me wondering if there was a way to at least get some colorization, more specifically HTML colorization. I wandered around in the options of VS2010, and eventually found the place where I could map an extension to a different colorization.

This is how you get HTML colorization in .cshtml files:

  1. Open Tools menu.
  2. Choose Options…
  3. Go to Text Editor, and third choice; File Extension.
  4. Enter cshtml as Extension and choose HTML Editor in the dropdown.
  5. Click Add and OK. Now try to open a .cshtml file – you should get HTML colorization.

Remember to remove this setting when VS2010 officially gets Razor colorization and IntelliSense.

That’s it. Hopefully it will be a little bit easier on your eyes.

Read More »

Client-Side Validation Using xVal and ASP.NET MVC 2

Posted on 31 March 2010 and tagged with , 3 comments

Validating input on the server-side in ASP.NET MVC 2 is quite easy when using the new Data Annotations on our Model classes. It means that we have automatic validation every time someone submits data to our Controller, the model binder of ASP.NET MVC will take care of running the validation rules we set up in the model.

However the problem arises when we want client side validation on our model. We don’t want to repeat our validation rules to a client side library as that will be a pain in the ass to maintain later, when the model changes. What we do want is something that is using our preexisting rules in a way that the client side library understands.

This is where xVal enters the game. It does exactly what I just described, which is converting our Data Annotation attribute-rules to rules which the excellent jQuery Validation plugin can understand. To give an example of how you can implement xVal with ASP.NET MVC, I will create a user registration form which will feature a few standard validation rules.

Validating a user registration form

Begin with downloading xVal library from CodePlex and reference the file from our new and empty ASP.NET MVC 2 project in Visual Studio. Also add the xVal.jquery.validate.js file to our scripts folder. We need a user class to play with. Add a class named User in the Models folder and add the following code.

[MetadataType(typeof(UserMetadata))]
public class User {
    public string Username { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    private class UserMetadata {
        [Required, StringLength(30)]            
        public object Username { get; set; }

        [Required, StringLength(30)]
        public string Password { get; set; }

        [Required, DataType(DataType.EmailAddress)]
        public object Email { get; set; }
    }
}

This will require a user to enter a username, password and email address. Username and password will require a maximum of 30 characters long and the name field will be optional.

We got the model, but we need somewhere to store them. For this simple demo I will be creating a dummy repository class which saves the user objects in memory, like the following snippet.

public class UserRepository {
    readonly List<User> _users = new List<User>();

    public void Create(User user) {
        // Save to database
        _users.Add(user);
    }
}

Now we need a controller and actions for our registration form. Two Register actions will be created – one for the GET and one for the POST. The GET will simply return a View and display a registration form, with the fields of our model. When submitting the form we will get to our POST action method which will check the ModelState.IsValid property if the input data is valid, if not the method will return the View, with supplied data. Otherwise the user object is saved to our dummy database and the user is redirected to the success page.

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

[HttpPost]
public ActionResult Register(User user) {
    if (!ModelState.IsValid)
        return View(user);

    _userRepository.Create(user);

    return RedirectToAction("Registered");
}

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

If you have created the View files for these actions you should be having a fully functional registration form, with server-side validation.

Magically turn on client-side validation

The server-side validation is working, and all we ever want now is client-side validation! The steps to make that work is so easy it is laughable. We only need to include these script files in the head section.

<script src="/scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/scripts/xval.jquery.validate.js" type="text/javascript"></script>

Client Side Validation with xValLastly we need to tell xVal to output the Data Annotation rules to our page, so that it can be read by JavaScript. This is very easily done with the following HtmlHelper method, at the bottom of our View page:

<%= Html.ClientSideValidation<User>() %>

That’s all!? Yes, in fact that is all we have to do, to get client-side validation in ASP.NET MVC 2. Try it out, and then get back here to see what more ways you can customize xVal.

Remote validation

Sometimes only client-side validation is not enough to validate certain properties of a model. We need to validate business rules which uses a database to validate. In these cases it can be really useful to move the validation back to the server, but still keeping the snappy, instant validation that client-side validation gives us.

In xVal this is possible through something that is called RemoteRule. To create a Remote Rule you only need to create a new Action method in your Controller, which receives the model, validates it, and finally returns a true/false result. In our project we will check if a username is already taken, so that two users can’t have the same username. We will start with the following Action method:

public RemoteValidationResult UsernameIsTaken(User user) {
    var exists = _userRepository.ExistsUsername(user.Username);
    return exists
        ? RemoteValidationResult.Failure("Username is already taken.")
        : RemoteValidationResult.Success;
}

I also updated the UserRepository class to include an ExistsUsername method which returns true if the username starts with “yadda”.

To register the Remote Rule with xVal we need to open the “Register” view and find the ClientSideValidation method we used earlier, and run a method on the returned object.

<%= Html.ClientSideValidation<User>()
    .AddRule("Username", new RemoteRule(Url.Action("UsernameIsTaken"))) %>

Remote Validation is now hooked up and you can try it out by typing “yadda” in the username field. It should then say the username is taken when you tab out of the field. Awesomely easy!

Custom attributes with client-side validation

In those cases where you do not need remote validation but only classic JavaScript validation will do just fine, then creating a new Data Annotation attribute is a good idea. We will use this technique when validating if a password is good-enough for us.

We will start with a new class, that inherit from ValidationAttribute (from Data Annotation) and implements the ICustomRule interface (from xVal). From the inherited class you will override the IsValid method which does the actual validation. In this case we will use Regular Expressions to determine if the password is decent. The other method, which we got from the ICustomRule interface will tell xVal which JavaScript function to run when doing the client-side validation. I have named it “GoodPassword”, and it won’t receive any parameters (null). If the validation fails, it will use the error message set in the constructor.

public class GoodPasswordAttribute : ValidationAttribute, ICustomRule {
    public GoodPasswordAttribute() {
        ErrorMessage = "Enter a better password.";
    }

    public override bool IsValid(object value) {
        if (!(value is string))
            return false;

        // Requires passwords to have atleast 5 chars and one number
        return Regex.IsMatch(value.ToString(), @"^.*(?=.{5})(?=.*\d)(?=.*\w).*$");
    }

    public CustomRule ToCustomRule() {
        // First parameter is the JavaScript function name
        return new CustomRule("GoodPassword", null, ErrorMessage);
    }
}

Finally the last thing is implementing the JavaScript function, which will use the same regex pattern as the server-side. The pattern could have been sent over to the JavaScript function through a parameter, but I wanted to keep them separate incase the JavaScript version needed modifications. Following is the last snippet showing the final JavaScript function.

function GoodPassword(value, element, params) {
    var regex = /^.*(?=.{5})(?=.*\d)(?=.*\w).*$/g;
    return (value.match(regex) != null);
}

Now try this in the form by typing passwords such as “monster2” and “foo”. We have got both client-side validation and server-side validation of our custom rule!

Summary

In this post we have covered how to implement basic client-side and server-side validation using xVal, jQuery Validation and Data Annotation in ASP.NET MVC 2. We also went further and created remote validation and custom rules for both server-side and client-side. See the demo link below for a quick look how it turned out, and download the source for a closer look.

View the demo
Download the source

Read More »

Create Your Own Blog Engine or Use an Existing?

Posted on 14 February 2010 and tagged with , 4 comments

Today, the 14th of February, I began my blog journey that I have been thinking of doing for the last couple of months. In my first post I will be talking about the question all blog writers ask before they start a blog - “which blog engine should I use?” – and I am no exception. I spent a couple of weeks thinking and searching for the right blog engine and this is what I found.

Requirements for my blog

Before I began my research I had a set of requirements that I wanted my blog to handle. Firstly I wanted it to be written in a language I understand, so that I could easily configure it to my needs. The language I am the most comfortable with is C# in the .NET framework by Microsoft. This choice decreased the number of options I had to choose from a lot, and of course also removed the obvious choice of Wordpress which the majority of the blog sphere run.

My next requirement was to be able to easily customize the design and not have to set with the authors own design. Part of this requirement was also to have a nice and clean HTML source view (which you see through “view-source” in your browser). You may think this is totally unnecessary as the page can both look nice and be functional even with an ugly source view – but this is an obsession of mine and I still think it shows a degree of professionalism to have nicely formatted and valid HTML in your websites. This meant I had to throw away almost all of the major blog engines as they are built with ASP.NET Web Forms which has a lot of messy ID attributes, lots of script tags and large View State string lurking in the source. It should be noted though, that many of the blog engines have done a great job at correcting this, but still not enough for me! The skinning part I didn’t look into that much as the blog engines had already failed at another part of my requirements.

Following on I wanted a simple content management system (CMS) for displaying a about-page and listing projects I have created. This is covered by almost all blog engines out there, but I also wanted to be able to create my own dynamic pages (created with ASP.NET MVC) to run alongside the blog. This would most likely get messy and hard to maintain, having two different systems running in the same application.

Nice to have features

These three things was the major requirements I had, but I also had a few nice-to-have features. Like friendly URLs, support for MetaWeblog API and Windows Live Writer, OpenID login to comment and if possible written in ASP.NET MVC.

Finally making a decision

After going through several ASP.NET blog engines – more specifically Subtext, DasBlog, BlogEngine.NET and Oxite – I made the decision to abandon them all! I’m making my own blog engine and have it exactly like I want it. I might not get all the cool features like Trackbacks, Pingback and fancy admin system with statistics – but I will have something I can develop from time to time when I need new features.

Working on and off, it took about a month to create the blog with all the features mentioned above and a simple design. I also gave it a silly name – FriendlyBlog – to be able to refer to it easier. It is created with the ASP.NET MVC framework which lets me separate (most) logic from the presentation layer and have a clean source. I implemented the MetaWeblog API so that I can easily create posts with the excellent Windows Live Writer software. I’m using OpenID for comments which hopefully helps a bit against spam and yet is easy for users to use, and if it doesn’t help I can use Akismet. The blog engine also has Friendly URLs, but that can hardly be called a feature when using ASP.NET MVC, as it is too easy to get.

I’m now looking forward to using my new, shiny, blog engine to share my experience and thoughts in different technical areas.

Read More »

Loading Posts...