Hire Asp.Net Core developers

Why we need Templated Helper?

When we use the HTML method, such as LabelFor() and TextBoxFor(), it returns the model proprieties in a structured way. For example, the HTML Helper TextBoxFor () method, does have a text field that displays the value of the model, the assets-to-edit. 

If we want more control over the data that will be presented to the user or to edit the value. For example, if we have a value-for-money, at that time, we will have a currency sign to the label. With the help of an HTML helper is a method, such as ad LabelFor (), it is not possible. 

For this kind of problem ASP.NET MVC provides the concept of Templated Helper with the help of Templated Helper we’ll be able to implement this type of thing.

Types of Templated Helpers

Having fine support for Test Driven Development, MVC offers magnificent as well as tightly secured development features. When it comes to Templated helpers, it has two types of HTML helper 

  1. Editor Template
  2. Display Template

You can also create your own custom templated helper.

Types of Editor Templated Helper

There are three types of Editor Templated Helper. They are as follow –

  1. @Html.Editor(“Some_Data”) 
  2. @Html.EditorFor(model => model)
  3. @Html.EditorforModel()

Types of Display Templated Helper

There are three types of Display Templated Helper. They are as follow

  1. @Html.Display(“Some_Data”) –  This type of helper is used with a view that is not strongly typed. For example, if you use data that is stored in a ViewData or ViewBag, then you can use this templated helper with the help of the key, which is used to get the data to save it in the ViewData or ViewBag.  
  1. @Html.DisplayFor(model => model) – This type of helper is used by a strongly-typed view. If this model has features that are complex objects, it is very useful.
  1. @Html.DisplayForModel() – This type of helper is used by a strongly-typed view. This is a tool that utilizes every feature of the model is the object in view.

Use Templated Helper in ASP. NET MVC

For understanding this templated helper we need a model class. This is my model class

Book.cs

namespace LIBData

{

   public class Book

    {

        public int Id { get; set; }

        public string books_Name { get; set; }

        public string Image_path { get; set; }

        public string books_author { get; set; }

        public int books_isbn { get; set; }

        public int books_qty { get; set; }

    }

}

Creating Controller 

Now we need to create BookController and create Index Action Method to retrieve data. Here I use the ViewData to store our retrieved data.

BookController

 public class BooksController: Controller

    {

        private LibraryDbContext db = new LibraryDbContext();

        public ActionResult Index()

        {

            var record = db.Books.Select( b => b.books_Name).FirstOrDefault() ;

            ViewData[“Book_data”] = record;

            return View();

        }

}

Creating a view for @Html.Display()

@Html.Display(“Book_data”) template helper method returns the data. You can see the view does not model associated with it. so it is not a strongly-typed view.

@model IEnumerable<LIBData.Book>

@{

    ViewBag.Title = “Index”;

    Layout = “~/Views/Shared/LibAdmin.cshtml”;

}

<div class=”content mt-3″>

    <div class=”animated fadeIn”>

        <div class=”row”>

            <div class=”col-lg-12″>

                <div class=”card”>

                    <div class=”card-header bg-dark”>

                        <strong class=”card-title” style=”color : white;”>Books…</strong>

                        <div class=”float-right”> </div>

                    </div>

                    <div class=”card-body”>

                        @Html.ActionLink(“Create”, “Create”, new { }, new { @class = “btn btn-success” }) <br /><br />

                        <fieldset>

                            <legend> Book Details..</legend>

                            @Html.Display(“Book_data”);

                        </fieldset>

                  </div>

                </div>

            </div>

        </div>

</div>

</div>

Now run the code and see the following screen.

[Fig :- @Html.Display()]

@Html.DisplayForModel(model => model) and @Html.DisplayFor()

 public ActionResult Index()

        {

            var record = db.Books.Select( b => b.books_Name).FirstOrDefault() ;

            return View(record);

        }

Create a view for the Index method with a scaffold template. A scaffold template is a strong type view. when you add a scaffold template this looks like the following code. I will apply some style to it.

Index.cshtml

@model IEnumerable<LIBData.Book>

@{

    ViewBag.Title = “Index”;

    Layout = “~/Views/Shared/LibAdmin.cshtml”;

}

<div class=”content mt-3″>

    <div class=”animated fadeIn”>

        <div class=”row”>

            <div class=”col-lg-12″>

                <div class=”card”>

                    <div class=”card-header bg-dark”>

                        <strong class=”card-title” style=”color : white;”>Books…</strong>

                        <div class=”float-right”> </div>

                    </div>

                    <div class=”card-body”>

                        @Html.ActionLink(“Create”, “Create”, new { }, new { @class = “btn btn-success” }) <br /><br />

                        <table class=”table”>

                          <tr>

                             <th>

                                 @Html.DisplayNameFor(model => model.books_Name)

                             </th>

                             <th>

                                 @Html.DisplayNameFor(model => model.books_author)

                             </th>

                             <th>

                                @Html.DisplayNameFor(model => model.books_isbn)

                             </th>

                             <th>

                                @Html.DisplayNameFor(model => model.books_qty)

                             </th>

                            </tr>

                      @foreach (var item in Model)

                        {

                           <tr>

                             <td>

                              <img src=”~/imag/@item.Image_path” width=”100px” height=”120px” />

                              </td>

                              <td>

                                 @Html.DisplayFor(modelItem => item.books_Name)

                              </td>

                              <td>

                                 @Html.DisplayFor(modelItem => item.books_author)

                              </td>

                              <td>

                                @Html.DisplayFor(modelItem => item.books_isbn)

                              </td>

                               <td>

                                 @Html.DisplayFor(modelItem => item.books_qty)

                               </td>

                               <td>

                                  @Html.ActionLink(“Edit”, “Edit”, new { id = item.Id }, new { @class = “btn btn-success” })

                                  @Html.ActionLink(“Delete”, “Delete”, new { id = item.Id }, new { @class = “btn btn-danger” })

                                </td>

                                </tr>

                            }

                        </table>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>

Instead of this code, we can use the Display template. The view code like this.

@model IEnumerable<LIBData.Book>

<div class=”content mt-3″>

    <div class=”animated fadeIn”>

        <div class=”row”>

            <div class=”col-lg-12″>

                <div class=”card”>

                    <div class=”card-header bg-dark”>

                        <strong class=”card-title” style=”color : white;”>Books…</strong>

                        <div class=”float-right”> </div>

                    </div>

                    <div class=”card-body”>

                        @Html.ActionLink(“Create”, “Create”, new { }, new { @class = “btn btn-success” }) <br /><br />

<fieldset>

                            <legend> Book Details..</legend>

@Html.DisplayForModel() 

                        </fieldset>

                 </div>

                </div>

            </div>

        </div>

    </div>

</div>

Instead of DisplayForModel() you can use Html.DisplayFor(model => model)

<fieldset>

         <legend> Book Details..</legend>

@Html.DisplayFor(model => model)

</fieldset>

@Html.EditorForModel()

The Editor template helper is similar to as we use display template helper. now we implement the Editor template helper for our Edit action method of Bookcontroller, the controller is shown as below.

public ActionResult Edit(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Book book = db.Books.Find(id);

            if (book == null)

            {

                return HttpNotFound();

            }

            return View(book);

        }

        [HttpPost]

        [ValidateAntiForgeryToken]

   public ActionResult Edit([Bind(Include = “Id,books_Name,books_author,books_isbn,books_qty”)] Book book)

        {

            if (ModelState.IsValid)

            {

                db.Entry(book).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction(“Index”);

            }

            return View(book);

        }

Now we need to implement the Edit. cs method. Change the Edit scaffolding template with the following code.

Edit.cshtml

@model LIBData.Book

@{

    ViewBag.Title = “Edit”;

    Layout = “~/Views/Shared/LibAdmin.cshtml”;

}

<div class=”container”>

    <div class=”card”>

       <div class=”card-header bg-dark”>

            <strong class=”card-title” style=”color : white;”> Edit Books Details</strong>

        </div>

        <div class=”card-body”>

            @using (Html.BeginForm())

            {

                @Html.AntiForgeryToken()

            <div class=”form-horizontal”>

                <h4>Books</h4>

                <hr />

                @Html.ValidationSummary(true, “”, new { @class = “text-danger” })

                <div class=”form-group”>

                    @Html.EditorForModel()

                </div>

                <div class=”form-group”>

                    <div class=”col-md-offset-2 col-md-10″>

                        <input type=”submit” value=”Edit” class=”btn btn-success” />

                    </div>

                </div>

            </div>

            }

        </div>

    </div>

</div>

<div>

    @Html.ActionLink(“Back to List”, “Index”)

</div>

Now run the code and see the following screen. You can see that I do not use any database column name for our editor template. Use the only @HtmlEditorForModel().

[Fig :- @Html.EditorForModel()]

Conclusion 

Template helpers provide an automated way to provide a user interface that is based on a model of the data that is pointed to by the attributes that are defined in the system.ComponentModel. DataAnnotations namespace.

A templated helper can then automatically render the property value as we specified by using a control designed for the member, instead of using the default rendering.

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.

Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals. 

Hire Asp.Net Core developers from iFour Technolab to get your requirements done.

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.