1

For learning DisplayTemplates, I created a “String” DisplayTemplate as listed below. It is expected to append the word “Hello” after the model’s string value. But it is showing only the word “Hello”. How do we correct it?

Note: String.cshtml is added under Views\Contact\DisplayTemplates

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

CONTROLLER

public class ContactController : Controller
{

    // GET: /Contact/Details/5
    public ActionResult Details(int id)
    {
        Contact myContact = new Contact();
        myContact.FirstName = "Lijo";
        myContact.LastName = "Cheeran";
        myContact.Age = 26;

        return View(myContact);

    }

}

Detail View

@model MyDisplayAndEditorTemplateTEST.Contact

<fieldset>
<legend>Contact</legend>

<div class="display-label" style="font-weight:bold" >FirstName</div>
<div class="display-field">
    @Html.DisplayFor(model => model.FirstName)
</div>

<div class="display-label" style="font-weight:bold">LastName</div>
<div class="display-field">
    @Html.DisplayFor(model => model.LastName)
</div>

<div class="display-label" style="font-weight:bold">Age</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Age)
</div>

Partail Page for String DisplayTemplate (String.cshtml)

<%= Html.Encode(Model) %> Hello!

@Darin. For the editor template, I used @Html.EditorFor(model => model.FirstName). Still it is coming as a label as shown below. How do we change it to get it as a textbox?

Details.cshtml

@model MyDisplayAndEditorTemplateTEST.Contact

<fieldset>
<legend>Contact</legend>

<div>FirstName</div>
<div>
     @Html.EditorFor(model => model.FirstName)
</div>

<div class="display-label" style="font-weight:bold">LastName</div>
<div class="display-field">
    @Html.DisplayFor(model => model.LastName)
</div>

EditorTemplate

@Model TEST

DisplayTemplate

Hello! @Model

enter image description here

1 Answer 1

5

<%= Html.Encode(Model) %> Hello! is WebForms syntax. Make sure you are not confusing the 2 view engines. So put the following in your string.cshtml Razor display template:

@Model Hello!
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. That works. One more question - How do I make similar thing for EditorFor? When I used the same, it is coming as label; not textbox.
@Lijo, you use ~/Views/Contact/EditorTemplates/String.cshtml and then you use Html.EditorFor instead of Html.DisplayFor in your view.
Marking as answer since it address the problem originally posted. I have other problems as listed as separate entry here, below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.