Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
What is the difference between EdiotFor and Displayfor(Templated HTML Helpers) in MVC?
Posted

Hi,

EditorFor -If the property is typed as a primitive type (integer, string, and so on), the method renders an HTML input element for a text box

DisplayFor - If the property is typed as a primitive type (integer, string, and so on), the method renders a string that represents the property value

e.g. If we have EmployeeModel as below -
C#
public class EmployeeModel
{
    [Display(Name = "Employee ID :")]
    public int Id { get; set; }
    [Display(Name = "Employee Name :")]
    public string Name { get; set; }
    [Display(Name = "DOJ :")]
    [DisplayFormat(DataFormatString = "{0:dd-mm-yyyy}")]
    public DateTime DateOfJoining { get; set; }
}


Then on view we have,

HTML
@using (Html.BeginForm())
{
    <h2>EditorFor Implementation</h2>
    @Html.LabelFor(m=>m.Id)
    @Html.EditorFor(m=>m.Id)
    
    @Html.LabelFor(m=>m.Name)
    @Html.EditorFor(m => m.Name)
    // This will render Input box with value of property
    @Html.LabelFor(m=>m.DateOfJoining)
    @Html.EditorFor(m => m.DateOfJoining) 

    <hr />

    <h2>DisplayFor  Implementation</h2>
    @Html.LabelFor(m=>m.Id)
    @Html.DisplayFor(m=>m.Id)
    
    @Html.LabelFor(m=>m.Name)
    @Html.DisplayFor(m=>m.Name)
    
     // This will render string object with value formatted as in DisplayFormat if specified
    @Html.LabelFor(m=>m.DateOfJoining)
    @Html.DisplayFor(m=>m.DateOfJoining)
}


I am not sure if I can attach screenshot here for reference, but this what i get from view source for above code.

For EditorFor will render input control as below -
HTML
<label for="DateOfJoining">DOJ :</label><input class="text-box single-line" data-val="true" data-val-date="The field DOJ : must be a date." data-val-required="The DOJ : field is required." id="DateOfJoining" name="DateOfJoining" type="datetime" value="7/8/2015 12:00:00 AM" />


For DisplauFor will render string as below -
HTML
<label for="DateOfJoining">DOJ :</label>08-00-2015


Hope this helps.
 
Share this answer
 
v2
Comments
AnvisNet 9-Jul-15 6:37am    
Thanks I got the idea :)
I think your question is related to this post. Please have a look this may help you to better understand about your question.


http://stackoverflow.com/questions/6365633/what-is-the-html-displayfor-syntax-for

 
Share this answer
 
v2
Comments
AnvisNet 8-Jul-15 6:19am    
here I am looking for the difference between displayfor and editorfor, I do know what they both do, And they do produce same output as I am concerned. So whats the difference between them?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900