2011-10-09 99 views
0

我有以下視圖模型:爲什麼不編輯爲呈現HTML?

public class ShowMatrixQuestionViewModel : ShowQuestionViewModel 
{ 

public Dictionary<MatrixRows, List<MatrixColumns>> columnrow; 
public List<MatrixColumns> columns; 
public List<MatrixRows> rows; 

public ShowMatrixQuestionViewModel() 
{ 
    columns = new List<MatrixColumns>(); 
    rows = new List<MatrixRows>(); 
    columnrow = new Dictionary<MatrixRows, List<MatrixColumns>>(); 
} 
} 

public class MatrixColumns 
{ 
    public int Column_ID { get; set; } 
    public int Column_Number { get; set; } 
    public String Column_Description { get; set; } 
    public Boolean IsAnswer { get; set; } 
} 

public class MatrixRows 
{ 
    public int Row_Id { get; set; } 
    public String Row_Number { get; set; } 
    public String Row_Description { get; set; } 
} 

當我填寫了我的模型,並嘗試用DisplayTemplate它不顯示任何東西來顯示MatrixRows。我DisplayTemplate的名稱是MatrixRows.cshtml它放在裏面查看/共享/ DisplayTemplates

這是我用來顯示MatrixRow代碼:

@model TestInheritance.Models.ShowMatrixQuestionViewModel 

@using (Html.BeginForm()) 
{ 
    <div id="edit"> 
    <h2>Columns</h2> 
    @foreach (var column in Model.columns) 
    { 
     <p>@column.GetType().Name</p> 
     Html.RenderPartial("EditMatrixColumn", column); 
    } 
    <h2>Rows</h2> 
    @foreach (var rows in Model.rows) 
    { 
     <p>@rows.GetType()</p> 
     Html.DisplayFor(x => rows); 
     //Html.RenderPartial("EditMatrixRow", rows); 
    } 
    </div> 

    <input type="submit" value="Finished" /> 
} 

當我使用的RenderPartial它工作正常.. 。 我究竟做錯了什麼?

的DisplayTemplate代碼:

@model TestInheritance.Models.MatrixRows 
@using TestInheritance.Helpers 

<div class="editrow"> 
@using (Html.BeginCollectionItem("rows")) 
{ 
    <span> 
    Nummer: 
    @Html.EditorFor(cn => Model.Row_Number) 
    </span> 
    <br /> 
    <span> 
    Beskrivelse: 
    @Html.EditorFor(bs => Model.Row_Description) 
    </span> 
} 
</div> 

回答

5

Html.DisplayFor返回HTML。
你沒有對HTML做任何事情。

你可能想通過寫@Html.DisplayFor(...)

2

而是寫來寫頁面循環:

@foreach (var rows in Model.rows) 
{ 
    <p>@rows.GetType()</p> 
    Html.DisplayFor(x => rows); 
} 

簡單:

@Html.DisplayFor(x => x.rows) 

,然後將相應的顯示模板~/Views/Shared/DisplayTemplates/MatrixRows.cshtml其內會自動呈現爲集合中的每個元素:

@using TestInheritance.Helpers 
@model TestInheritance.Models.MatrixRows 

<p>@GetType()</p> 
<div class="editrow"> 
@using (Html.BeginCollectionItem("rows")) 
{ 
    <span> 
     Nummer: 
     @Html.EditorFor(x => x.Row_Number) 
    </span> 
    <br /> 
    <span> 
     Beskrivelse: 
     @Html.EditorFor(x => x.Row_Description) 
    </span> 
} 
</div> 

這就是說,您的顯示模板看起來更像是一個編輯器模板,因爲它包含輸入字段。所以:

@Html.EditorFor(x => x.rows) 

然後用~/Views/Shared/EditorTemplates/MatrixRows.cshtml

+0

我不知道for循環的arent neccesary。 SLaKs在你面前回答,所以我必須給他提供這個觀點,因爲他的回答也是正確的。感謝您提供有用的提示! – Kenci