4

我試圖構建一個使用部分視圖和顯示/ editortemplates和Kendo ui的asp.net mvc 4應用程序。 我有一個特定的頁面視圖模型一:嘗試訪問displaytemplate中父視圖模型的屬性

public class Plant { 
    public Guid PlantId{ get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public ICollection<Leaf> Leafs{ get; set; } 
    public ICollection<Flower> Flowers{ get; set; } 
    public ICollection<Bug> Bugs{ get; set; } 
} 

而且還有葉,花的錯誤有自己的屬性。 例如:

public class Leaf { 
    public Guid LeafId{ get; set; } 
    public string Name { get; set; } 
    public string Documentation { get; set; } 
    public string Description { get; set; } 
} 

我利用partialviews在我看來,因此使得它更容易使用Ajax更新它們。 我的普通視圖:PlantDetail.cshtml

@model Plant 

<table> 
<tr> 
    <td> 
     <h2>@Html.Label(Resources.PlantDetailTitle)</h2> 
    </td> 
    <td> 
     @Html.HiddenFor(m => m.PlantId) 
     @Html.DisplayFor(m => m.Name) 
    </td> 
</tr> 
<tr> 
    <td>@Html.LabelFor(m => m.Description) 
    </td> 
    <td> 
     @Html.DisplayFor(m => m.Description) 
    </td> 
</tr> 
</table> 

@{Html.RenderPartial("_flowers", Model);} 

@{Html.RenderPartial("_leafs", Model);} 

在我的局部視圖「_leafs」(以及在「_flowers」我有一個調用需要的LeafId和PlantId的操作按鈕的意甲:

局部視圖 「_leafs」:

@model List<Leaf> 

@for (int i = 0; i < Model.Count(); i++) 
    { 
    @(Html.DisplayFor(m => m[i])) 
} 

我displayTemplate 「Leaf.cshtml」:

@model Leaf 
    @Html.HiddenFor(m =>m.LeafId) 
    <a class='k-button k-button-icontext' [email protected]("InitiateLeaf", "Plant") +"?  
    [email protected]&plantId=#=PlantId#">@Model.Name</a> 

現在我的問題是,我似乎無法在我的顯示模板中訪問我的父視圖的PlantId。 (並且我在每個顯示模板中都有同樣的問題..) 我已經在我的url.action中嘗試過使用routevalues,並且我知道我最終可以訪問JavaScript中的PlantId,但是是否有任何(mvc)方式繼續使用displaytemplates,不要複製我的plantId作爲我的孩子Leaf viewmodel的屬性?

我媒體鏈接試圖存取權限我parentviewcontext以「@ HttpContext.Current.Request.RequestContext.RouteData.Values [」控制器「]。的ToString()」像 在我displaytemplate,但似乎不是找到我的PlantId的價值(如果它甚至存儲在那裏..)。

其他人還有一些建議嗎?

+0

您是否找到了解決方案? –

回答

1

你提到的一個選擇是使用jquery訪問父級PlantId。如果您需要訪問父級的屬性,那麼最好設計您的視圖模型,類似於Entity框架如何建議我們創建模型類。

public class Plant { 
    public Guid PlantId{ get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public ICollection<Leaf> Leafs{ get; set; } 
    public ICollection<Flower> Flowers{ get; set; } 
    public ICollection<Bug> Bugs{ get; set; } 
} 

因此,你的葉類也應該有一個導航屬性返回到植物。

public class Leaf { 
    public Guid LeafId{ get; set; } 
    public string Name { get; set; } 
    public string Documentation { get; set; } 
    public string Description { get; set; } 
    public virtual Plant Plant { get; set; } 
    public Guid PlantId { get; set; } 
} 

確保在創建ViewModel時填充Plant屬性和PlantId。希望這可以幫助