w3resource

HtmlHelper Editor


In our last tutorials, we have discussed some HtmlHelper methods that can be used to generate different input form elements. In this tutorial, we will discuss another HtmlHelper method, which can generate an input for element based on the data type of the model property passed to it.

Editor() and EditorFor() extension method generates html input elements based on the data type of the model object's property passed.

The following table enumerates the html element created for each data type by Editor() or EditorFor() HtmlHelper method.

Property DataType Html Element
string <input type="text" >
int <input type="number" >
decimal,float <input type="text" >
boolean <input type="checkbox" >
Enum <input type="text" >
DateTime <input type="datetime" >

To illustrate the use of these two helper methods, we will use the following model class.

//Example: Activity Model
public class Activity
{
    public int Id { get; set; }
    public string ActivityName { get; set; }
    public int Duration { get; set; }
    public bool isCompleted { get; set; }
    public string AssignedTo { get; set; }
    public DateTime DateAssigned { get; set; }
}

Editor()

Editor() method requires a string expression parameter to specify the property name. It creates a html element based on the datatype of the specified property.

Editor() signature: MvcHtmlString Editor(string propertyname)

Consider the following example to understand the Editor() method works:

Example: Editor() in Razor view

Activity ID: @Html.Editor("Id")
Activity Name: @Html.Editor("ActivityName")
Duration: @Html.Editor("Duration")
Completed: @Html.Editor("isCompleted")
Assigned To: @Html.Editor("AssignedTo")
Date Assigned: @Html.Editor("DateAssigned")

In the above example, we have specified property names of Activity model as a string. So, Editor() method created the appropriate input elements based on the datatype as shown in the above figure.

EditorFor

EditorFor() method is a strongly typed method. It requires the lambda expression to specify a property of the model object.

EditorFor() signature: MvcHtmlString EditorFor(<Expression<Func<TModel,TValue>> expression)

//Example: EditorFor() in Razor view

Activity ID:      @Html.EditorFor(a => a.Id)
Activity Name:   @Html.EditorFor(a => a.ActivityName)
Duration:            @Html.EditorFor(a => a.Duration)
Completed:       @Html.EditorFor(m => a.isCompleted)
Asssigned To: @Html.EditorFor(m => a.AssignedTo)
Date Assigned:            @Html.EditorFor(m => a.DateAssigned)

In the above example of EditorFor() method, we have specified the property name using the lambda expression. The result would be the same as the Editor() method shown in the previous code snippet.



Inviting useful, relevant, well-written and unique guest posts