如果我理解正確的,你有一個單一的查看您想要在一個分部視圖中顯示資產列表的位置,以及在選定時編輯資產的另一個分部視圖。
首先你應該創建兩個部分視圖。
Assets.cshtml(部分圖)
@model IList<Models.Asset>
.. iterate the model and display the menu of assets
EditAsset.cshtml(部分圖)
@model Models.Asset
.. create the form and render the fields for editing
現在在主視圖Index.cshtml
您在使用Html.Partial/Html.RenderPartial
的Assets.cshtml
調用而另一個則在點擊資產鏈接時被調用。
索引。CSHTML
@Html.Partial("Assets", Model.Assets) @*rendering the partial view*@
... other html
<div id="editAssetContainer"> @*edit form placeholder*@
</div>
注意,你也應該有一個叫editAssetContainer
佔位符,你要去哪裏,以顯示編輯表單。
現在,待處理的事情是如何在佔位符中單擊資源鏈接來呈現編輯表單。你可以通過兩種方式做到這一點:直接使用jQuery或使用Ajax.ActionLink。您可以在Asset.cshtml
局部視圖中創建所有資產鏈接作爲ajax鏈接。 )如果您使用的是Ajax.ActionLink,請不要忘記包含不顯眼的ajax庫)
Ex。 Ajax.ActionLink
@Ajax.ActionLink(linkText,
"EditAsset", // the action that returns the partial view
new {assetId = @asset.Id }, // the assetId that to be passed to the action
new AjaxOptions // you can specify the targetid and others here..
{ UpdateTargetId = "editAssetContainer",
InsertionMode = InsertionMode.Replace
}
)
在這兩種情況下,你需要在返回EditAsset.cshtml
控制器的動作。
public PartialViewResult EditAsset(int assetId)
{
var asset = .. get asset using assetId from db.
return PartialView(asset);
}
UPDATE:
有兩種方法可以將模型加載到Assets.cshtml
局部視圖。第一種方法是創建一個包含資產列表作爲屬性的視圖模型,並用此視圖模型強制鍵入index
視圖。然後您可以撥打Html.Partial
將資產傳遞給它。
Ex。
public class IndexViewModel
{
public IList<Asset> Assets;
.. other properties if there any
}
Index.cshtml
@model IndexViewModel
@Html.Partial("Assets", Model.Assets).
第二的aproach是你可以有一個孩子的行動,獲得資產的從數據庫列表,並返回局部視圖。在這種情況下,您不需要強行鍵入Index
視圖。
[ChildActionOnly]
public PartialViewResult Assets()
{
var assets = .. get from db
return View(assets);
}
您甚至可以從Index
孩子行動
@Html.Action("Assets")
您可以用哪一個最適合你的。
很感謝。只是想知道資產局部視圖如何獲取其數據,它是否在控制器上擁有自己的操作方法。 [這個問題](http://stackoverflow.com/questions/1371031/asp-net-mvc-partial-view-controller-action)。建議索引具有列表並將其傳遞給partial,在這種情況下,index視圖需要與資產列表強制類型化。這是最好的方法嗎? –
對不起,我錯過了這麼說。儘管我更新了我的答案。 – VJAI