Editor templates: Tricks to build complex UI controls in ASP.NET MVC

ASP.Net MVC editor templates are a key for fast development. In ASP.NET you have any UI controls you need and a Drag-and-Drop does the magic and generates the Html codes for you. In contrast ASP.Net MVC requires writing the Html code manually or using the Html.Editor, and by that you implicitly use Editor Templates. There are default Editor Templates for basic UI controls. For example by calling Html.EditorFor on a string field, ASP.Net MVC loads the appropriate editor template, which in this case it is a simple input field. However Editor Templates are not just limited to basic data types; you can build an editor template for your complex data type. For instance you may have an Apple Model which is referenced in another model. You may want to build an engaging UI for the apple model and load that UI in other classes. You can build an editor template for the apple model and ASP.NET MVC takes care of the rest for you. Whenever you call the Html.EditorFor for the apple field of a class it loads the html code you used in the editor template file. In the rest of this tutorial first you learn the tricks to build a complex UI control like an Adder using editor templates and then we review the usages of Editor Template for custom UI controls

ASP.net MVC editor template for an Adder UI control

In my related entity update article I talked about the business codes required for a form which has an Adder for a list of data. In this article I’m going to teach you how to build the UI for an “Adder-Form” using ASP.Net MVC Editor Templates. Please have a look at the below picture to understand what we mean by adder form:

ASP.Net MVC editor templates

Figure 1

As you can see the traveler field of a reservation is a list. This list is being filled by guests' info. The user can add as many traveler as he wants by pressing the + button and filling in the inputs. In order to build the above form first you need an Editor Template for the traveler or Guest. After building the editor template building such form is as simple as calling Html.Editor method on fields. But remember if you do not build the editor template, ASP.Net MVC loads the default input type for the Guest collection:

    public class Guest

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string SurName { get; set; }

        public DateTime DateOfBirth { get; set; }

        public byte Gender { get; set; }

        public int ReservationId { get; set; }

        public Reservation Reservation { get; set; }

    }

    public class Reservation

    {

        public int Id { get; set; }

        public virtual ICollection<Guest> Guests { get; set; }

        public virtual ICollection<HotelServices> Services { get; set; }

    }

 

The first thing to note in defining the EditorTemplate is the name of an EditorTemplate which should be the name of Model. In this case it would be Guest.

@model Tutorials.Models.Guest 

@Html.HiddenFor(model => model.Id)

<fieldset class="first travelRow" id="[email protected](Model.Id)">

    <div class="field from">

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        @Html.TextBoxFor(model => model.FirstName, " ", new { @class = "text ui-autocomplete-input", placeholder = "First name" })

    </div>

 

    <div class="field">

        @Html.TextBoxFor(model => model.SurName, " ", new { @class = "text ui-autocomplete-input", placeholder = "Surname" })

    </div>

 

    <div class=" field datepicker cfdiv_datetime" id="input_datetime_21_container_div">

        @Html.TextBoxFor(model => model.DateOfBirth, " ", new { @class = "text dates datepicker cf_date_picker", placeholder = "Date of birth" })

        <div class="clear"></div>

        @Html.ValidationSummary()

    </div>

 

    <div class="field">

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        @Html.RadioButtonFor(model => model.Gender, " ")

    </div>

</fieldset>

 

You should place this Guest.cshtml code in Views/Shared/EditorTemplates folder. After Creating the Editor Template you can easily render the Guest Collection of Reservation Form by this line:

@Html.EditorFor(model => model.Guests)

This line and the internal Editor Template functionality of ASP.NET MVC handle your Edit form by loading the reservation and its Guests you prepare in the controller. For Create form you need the create Guest List with an empty Guest object and set it for Reservation Model.

The form without the Adder (+) button and its functionality has no usages. You should place the Adder button in the Reservation form and write a JavaScript to Add the inputs by pressing the + button.

  

     var travelerNum= 1; 

              jQuery(window).load(

                     function ()

                     {

                           jQuery("#addTravelerRow").click(

                                  function (){

                                         if     ( travelerNum >= 6)  {

                                                alert("The maximum number of travelers reached, you can not add any further travelers.");

                                         }

                                         else{

                                                travelerNum++;

                                                var ffbase = jQuery('<fieldset class="first travelRow extra-flight" id="traveler-0" data-travelerno="0"><div class="field from">       <input type="text" name="FirstName" class="text leavingFromField ui-autocomplete-input" data-travelerno="0" value="" id="Guests[0].FirstName" /></div><div class="field"><input type="text" name="SurName" class="text goingToField ui-autocomplete-input" data-travelerno="0" value="" id="Guests[0].SurName" /></div><div class="field datepicker"></div><div class="field"><input type="radio" id="guest-0" name="gender" value="male"  checked /> Male<input type="radio" id="guest-1" name="gender" value="female" /> Female</div> <div class="removeTravelerRow" id="remove"></div><div class="inlineHint" style=""></div>   </fieldset>');

                                                ffbase.attr("id","traveller-"+travelerNum);

                                                ffbase.attr("data-travellerno",travelerNum);

                                                var fromInp = jQuery("input[name=FirstName]", ffbase);

                                                var fromName = "Guests[" + travelerNum + "][FirstName]";

                                                fromInp.attr("name",fromName);

                                                fromInp.attr("data-travellerno",travelerNum);

                                                fromInp.attr("id", "Guests[" + travelerNum + "][FirstName]");

                                               

                                                fromInp = jQuery("input[name=SurName]", ffbase);

                                                fromName = "Guests[" + travelerNum + "][SurName]";

                                                fromInp.attr("name",fromName);

                                                fromInp.attr("data-travellerno",travelerNum);

                                                fromInp.attr("id", "Guests[" + travelerNum + "][SurName]");

                                               

                                                fromInp= jQuery("input[name=gender]",ffbase);

                                                fromName="Guests["+travelerNum+"][gender]";

                                                fromInp.attr("name",fromName);

                                                fromInp.attr("data-travellerno",travelerNum);

                                                fromInp.attr("id","Guests["+travelerNum+"][gender]");

                                                jQuery("#addTravelerRowWrapper").before(ffbase);

                                         }

                                  }

                           );

                     }

              );

 

The Java Script code is simple; we just created a template in ffbase variable and then we filled it with name, Id and etc. based on the travelerNum.

It's done now, the adder form is ready! You may wonder by having the java script code, why we needed the editor template. Well the editor template is used when your form has an error while submitting. Another usage is while you open the form in Edit mode. In both cases the editor template automatically loads the required number of inputs with their value for the traveler field. At the end you also have a neat code as a bonus.

Editor templates for custom ASP.NET MVC UI controls

 In the previous section you learned how to build an editor template for any model you want. In this section you see how you can use editor templates to build a custom UI control. These type of editor templates are more reusable because they are not tied to a special model for a special case. For example you may use strings to store the hex value of a color for a model. Although it is a string type you do not want to use default text input control for it. In this case you need a Color Picker UI. Building an editor template for the Color Picker allows you to reuse this color picker UI for your future projects. The process to build a color picker UI is simple, just Create a “Color” Editor Template and use [UIHint("Color ")] attribute above your Model field which is supposed to be filled with the hex code of the color.

Read 1341 times Last modified on Monday, 31 August 2015 05:01
Rate this item
4.67
(3 votes)
About Author
Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Advanced Programming Concepts
News Letter

Subscribe our Email News Letter to get Instant Update at anytime