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。希望这可以帮助