Thursday, 14 May 2015

Custom Editor Template for a complex type in MVC

Hi,

Here I am going to demonstrate, How we can create a custom editor template for a complex type.

Let's take a scenario, We are building a application where a student can choose subject he/she wants to learn. Student and Subjects information are available in database. Here is corresponding model classes for Student and Subject. This is just an example. public class Student { public string Name { get; set; } public string Class { get; set; } }

There are multiple ways of doing this and easy way to achieve this is using custom editor template. Here I have two model classes "Student" and "Subject" and I can use this model classes as it is, to bind with view. So what to do. Here is the way, We need to create a ViewModel (ViewModel is required when we have more than one model classes for View, as we need in this example.).
Here I am gonna define ViewModel:

What I did here?,First, Created a class which has property of Subject class type and a bool type property. Actually purpose of doing this is, "I need custom editor template for this complex type which basically will help us to achieve the kind of UI we need. Second, Created a class called StudentViewModel which will be used for binding for View.Third, Will create custom editor for complex type SubjectOpted.

and here are the steps to create Custom Editor Template for complex type:
1. Add a folder called "EditorTemplates"
2. Create a cshtml file with the name of complex type, in this case it will be SubjectsOpted.cshtml.
3. Add code for this view: @model MVCEditorTemplatesExample.Models.SubjectsOpted @Html.CheckBoxFor(m => m.OptedIn, new { @checked = "checked" }) @Html.HiddenFor(m => m.Subject.Id) @Html.HiddenFor(m => m.Subject.Name) @Html.DisplayFor(m => m.Subject.Name) <br />
4. Yeah, we are done with our custom Editor template for complex type.That's it. :)

Take a look of highlighted code here, this is how we need to call editor template. too tough isn't it :). Based on complex type and name we used for template, MVC is smart enough to decide what editor should be called.