简体   繁体   中英

ASP.NET MVC3: DisplayTemplates does not show model value (MVC3 Partial Page)

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

在此处输入图片说明

<%= 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM