Posted by: Terry Nederveld | February 16, 2011

EditorTemplates, DataAnnotations and Telerik, Oh my.

Lately I have been having some real fun using EditorTemplates, DataAnnotations and Telerik. So I decided it was time to share my experience. To start off let me tell you what versions I am using:

  • Visual Studio 2010 Ultimate
  • ASP.NET MVC3 RTM
  • Telerik Extensions for MVC Q3 2010 SP1

Let’s begin by creating a new MVC project. Select “ASP.NET MVC Web Application”.

After clicking “Ok” a new window introduced with MVC3 will appear. This is where you choose the project template, view engine and if you want to create a unit test project. For this sample I am choosing the “Internet Application” and the “Razor” view engine. If you haven’t used the Razor view engine, I suggest you try it out. I found that once you use it and get pass the urge to use <% %> it is actually faster typing.

Once it has finished creating your project you should have a Solution that looks very similar to the image on the right. If you hit F5 right now, it will build and run your new MVC3 site. Before you do that we have to add a few things in order for Telerik to work. If you don’t have the Telerik controls for .NET you can download the open source version from their website. I am using the same version as the open source one 2010.3.1318.

The controls are installed now we can finish adding the few items to the solution in order to get Telerik working with our project. First, I always go through Windows Explorer and navigate to the “Program Files (x86)\Telerik\Extensions for ASP.NET MVC Q3 2010”, if you are not using a 64bit OS it will be in “Program Files”. From there I will go into the “Content” and “Scripts” folders and copy the “2010.3.1318″ directories to those areas of my project. “Content\2010.3.1318” is copied to the “Content” and “Scripts\2010.3.1318” is copied to the “Scripts”. That is where the Telerik().ScriptRegistrar() and the Telerik().StyleSheetRegistrar() will look first for the files it needs.

Next add a reference to the Telerik DLL. Remember to select the correct DLL for the version of MVC you are using. Since this post is using MVC3, I will be selecting the MVC3 version of the Telerik controls. You can find the DLL in the Telerik folder under your program files inside the directory called “Binaries”. You will see three different folders under that one.

Some of the following are just ways that I prefer to do things, try them out maybe you will enjoy it. First up, I always create another project that will hold constant variables, formatting functions, and etc. I call it my “Core”, so I will add a new Class Library and name it “TelerikEditorTemplates.Core”. Then I will add my data access layer (DAL), I like to call it “Infrastructure”. Following in the previous steps footsteps, add a Class Library and name it “TelerikEditorTemplates.Infrastructure”. This sample project is not going to have any database associated with it. Now you may be asking yourself, why he does that. Well the answer is: I separate them out because if I need to make a change to the formatting that a function is doing or change a constant variable, there is no need to completely recompile the actual site, I can just recompile the specific project and push that DLL to the server. Once those two projects are created go ahead and “Add Reference” to them.

In the essence of time, leave the AccountModels.cs in its current project. Remember that the AccountModel.cs is not a complete membership provider, which is why I always roll my own version of it.

Moving on to the code, there is a few items that I always do with an MVC project most of which are added to the “_Layout.cshtml”. New to MVC3 and Razor then you may be asking: What is _Layout page?

You typically want to maintain a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept with a feature called “layouts” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

~ Scott Gu’s Blog (link here)

Now that you know what the _Layout page is. I always add a couple of @RenderSection sections to my _Layout page. These sections help me organize my view code into the right spots on the page when it is rendered out to the browser. The one thing that I can tell you here is: make sure to use the override that has the required parameter. Especially if the section won’t always have something to render from the view.

For the Telerik controls to work we must add several things to the _Layout page. First, in the <head/> section of the page we need to add the Telerik StyleSheetRegistrar. Below is the code used to get the default CSS. Telerik has many options to choose from for styles. If the default style is not what you want all that is needed to change is “telerik.default.css” to which ever style floats your boat.

Another item that is needed for the Telerik controls to work properly is the ScriptRegistrar. Telerik suggests that it is the last thing before your closing body tag. Remember you will need to tell it not to load jQuery if you are already including it in the head section of the page.

Moving on, wait all is not right? You are not able to see Telerik when you type @Html? That’s because we need a using statement. Try adding the following code to the top of the _Layout page. Does it work now?

Once all the items that needed to be in the _Layout page are added it’s time to create the model for whatever it is we want to do. For this post let’s create a model for a simple Contact form. That should be very straight forward. We’ll need the following: Name, Email, Subject, and Message. In the Core project we can create the an Interface object that will control what is needed in the Model.  Again, in the sample project I will show you how I normally create it for now go ahead and create a folder called “Models” in the Infrastructure project. This is where the model for the contact form will live. After you have created the folder right click it and select “Add -> Class” and call it “ContactFormModel.cs”. We will need to make it a public class in order for it to be used so go ahead and change that now. Go ahead and copy and paste the following into your class file.

 

 namespace  TelerikEditorTemplates.Infrastructure.Models
 {
     public  class  ContactFormModel 
     {
         public  string  Name { get ; set ; }
         public  string  Email { get ; set ; }
         public  string  Subject { get ; set ; }
         public  string  Message { get ; set ; }
     }
 }

 

After you add that to your class file make sure the project gets built. If it doesn’t, then when you go to create your view it will not show up in the Model Class combo box. Now open the HomeController.cs file and add a new ContactUs method. You can copy and paste the code below into your controller.

 

 public  ActionResult  ContactUs()
 {
     var  model = new  ContactFormModel ();
     return  View(model);
 }

You will need to also add a using statement to the “TelerikEditorTemplates.Infrastructure.Models” in order for this to compile properly.

Now we add a new view that will be rendered when someone accesses “/contactus”. This process is very easy, right click inside the ContactUs method and from the context menu go ahead and select “Add View” and it will open the “Add View” dialog. The view name will be automatically populated with the name of our method; if you change it you would need to specify in your method what view you want it to return. Check the box next to “Create strongly-typed view” and it will allow you to select a model for the view. One of the good changes with MVC3 is that this now shows the model names (ContactUsModel) instead of the fully qualified names (TelerikEditorTemplates.Infrastructure.Models.ContactUsModel). Go ahead and start typing the name of the model into the combo box. Now, before clicking “Add” choose the scaffold template “Create”.  Also, if you are not using a _ViewStart.cshtml file then you will need to select the _Layout page. Your dialog should look like the following image:

Once you click “Add” it will create the new view “/Views/Home/ContactUs.cshtml”. Before we can run the project we need to do one more thing. We need to add a link to the page in the _Layout page. Go ahead and find the _Layout page, it should be under the shared views directory. Open the file and add <li> element to the menu area with @Html.ActionLink(“Contact Us”, “ContactUs”, “Home”) as the inner text.

Finished adding that to the file? Good, go ahead and press F5 and it will build and run the project.  When it opens in your browser click the “Contact Us” item and it should look like the following:

Doesn’t quite look like a contact form does it? Let’s spruce it up a bit. From MVC2 to MVC3 Microsoft made another change that happened when the view was created, did you notice it? They no longer use Html.TextBoxFor(model => model.Name) anymore, instead Html.EditorFor(model => model.Name) is used. This was changed so we can utilize DataAnnotations in order to control what is outputted for each property type from the model.

Let’s go ahead and add some DataAnnotation attributes to the model properties. Before that can be done there must be a reference to System.ComponentModel.DataAnnotations and System.Web.Mvc in our Infrastructure project. Remember to get the correct version of the MVC DLL located in your Program Files. The first DataAnnotation we will add to the model is the “Display” attribute. The model should look like this:

If the “Display” doesn’t show up as an option in your intellisense more than likely the “using System.ComponentModel.DataAnnotations” statement was missing from the class file. Once you have all the display attributes added press F5 and navigate to the page in order to see the changes.

Did you notice that the labels have changed but we didn’t even touch the view? Have you seen a contact form that didn’t have any validation associated with it? No, me either. With that in mind our next DataAnnotation attributes to add will give us control over which properties of the model are required. To make a property required we only need to use the attribute [Required]. Instead of using the default required message add “ErrorMessage=” to the attribute to control the message displayed to the end user. An example would be [Required(ErrorMessage=”My message here”)] .

Along with labels and required fields there are many other attributes that can be used. Two attributes that control what is rendered to the browser are: [DataType] and [UIHint]. With MVC3 we now also have an easy way to allow a single property the ability to allow Html code without receiving the dreaded “Potentially unsafe characters” message. That attribute is [AllowHtml], it is not a part of DataAnnotations attributes. It was introduced in the MVC3 library. In order to use it there must be a using statement to System.Web.Mvc in the class file. I have gone ahead and added all the attributes we are going to use on our model, you can view the new additions below:

After these additions have been added to your model press F5. When you are on the ContactUs page go ahead and click the “Create” button. The validation has been automatically added to the view. It should look like the following:

Look at that, without even having to touch the code in the view our site now has validation. Now we are going to touch on another subject and it will involve Telerik and EditorTemplates. Before we can dive into it a directory needs to be created. In my humble opinion I like to have all the editor templates that for site wide use in the Shared folder under Views and if it is specific to a certain controller you can put it under that controllers directory in the Views folder. For now we are going to put this under the Shared folder. Go ahead and create the directory “EditorTemplates” under the Shared folder. Once that is created, right click and select “Add View” name it “Html”. Once it has created the view. We will want to remove all the code from it and replace it with the following code:

After that code has been saved in the “Html.cshtml” file. Go ahead press F5 and navigate to the ContactUs page. If all goes well you should now see the Telerik HTML editor on the page.

Now that you have base knowledge for creating an EditorTemplate with the Telerik controls you can actually create any type you need. In the past I have used EditorTemplates for rendering controls to input currency, date/time, email, and etc. Experiment with them and it won’t take long for you are hooked by the power of DataAnnotations and EditorTemplates.

You may click here to download the sample project.

Advertisements

Responses

  1. how i connect database for razor view.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: