ASP.NET MVC3:DisplayTemplates不显示模型值(MVC3 Partial Page)

时间:2012-02-20 07:54:14

标签: c# asp.net .net asp.net-mvc asp.net-mvc-3

为了学习DisplayTemplates,我创建了一个“String”DisplayTemplate,如下所示。期望在模型的字符串值之后附加单词“Hello”。但它只显示“你好”这个词。我们如何纠正它?

注意:在Views \ Contact \ DisplayTemplates

下添加了String.cshtml
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);

    }

}

详情视图

@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>

String DisplayTemplate(String.cshtml)的部分页面

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

@Darin。对于编辑器模板,我使用了@ Html.EditorFor(model =&gt; model.FirstName)。它仍然是一个标签,如下所示。我们如何更改它以将其作为文本框?

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 个答案:

答案 0 :(得分:5)

<%= Html.Encode(Model) %> Hello!是WebForms语法。确保您不会混淆2个视图引擎。请将以下内容放入您的string.cshtml Razor显示模板中:

@Model Hello!