[英]Render whole page with PartialView (and data) on page load
當前,我們有一個頁面,您可以在其中選擇一些參數並單擊按鈕以加載數據並將其顯示在網格中,但是尚無功能(通過url參數)在頁面加載時顯示數據。 我已經添加了必要的路由配置和Action,但是在呈現頁面時遇到了麻煩,它僅顯示不帶樣式的PartialView。
如何獲得整個頁面而不是PartialView的呈現?
以下是我為View和Controller編寫的簡單代碼。
查看/刨/ Index.cshtml
@model PlaningTool.Web.Models.PlaningViewModel
<div class="row">
<div>
@using (Ajax.BeginForm("GetDataRows",
"Planing",
new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId = "gridPlaceholder",
LoadingElementId = "loadingIndicator"
}))
{
<!-- some comboboxes to select project and year -->
<input type="submit" value="Load data" />
}
</div>
</div>
<div id="gridPlaceholder">
<div id="loadingIndicator" style="display: none;">
<img src="~/Content/images/loading-image.gif" />
</div>
</div>
控制器/ PlaningController.cs
public partial class PlaningController : Controller
{
public virtual ActionResult Index()
{
return View();
}
public virtual ActionResult Plan(long projectID, int year)
{
var viewModel = new PlaningViewModel
{
ProjectID = projectID,
Year = year
};
// return GetDataRows(viewModel);
return RedirectToAction("GetDataRows", viewModel);
}
[RestoreModelStateFromTempData(typeof(PartialViewResult))]
public virtual PartialViewResult GetDataRows(PlaningViewModel viewModel)
{
// Load data from database with viewModel.ProjectID
// and viewModel.Year as parameters
[...]
var vm = new PlaningViewModel
{
// Set ViewModel for loaded data
[...]
};
return PartialView("Shared/_PlaningViewModelRows", vm);
}
[...]
}
我終於找到了解決方案。 我很確定這不是執行此操作的最佳方法,但它確實有效。
如果已經設置了Model
則渲染PartialView
。
<div id="gridPlaceholder">
@{
if (Model != null)
{
Html.RenderPartial("Shared/_PDataViewModelRows", Model);
}
}
<div id="loadingIndicator" style="display: none;">
<img src="~/Content/kendo/Bootstrap/loading-image.gif"/>
</div>
</div>
在我的Controller
我已經更改為這個,所以我的ViewModel
被獨立加載,並且我只是使用新的ViewModel
返回與Index
相同的視圖。
public virtual ActionResult Plan(long projectID, int year)
{
var viewModel = new PlaningViewModel
{
ProjectID = projectID,
Year = year
};
return View("Index", LoadViewModel(viewModel));
}
public PlaningViewModel LoadViewModel(PlaningViewModel viewModel)
{
// Load data from database with viewModel.ProjectID
// and viewModel.Year as parameters
[...]
var vm = new PlaningViewModel
{
// Set ViewModel for loaded data
[...]
};
return vm;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.