在页面加载时使用PartialView(和数据)渲染整个页面

时间:2017-05-22 10:42:12

标签: c# asp.net .net asp.net-mvc

目前我们有一个页面,您可以在其中选择一些参数并单击按钮来加载数据并将其显示在网格中,但是没有功能可以在页面加载时显示数据(通过url参数)。我已经添加了必要的路由配置和操作,但是我在渲染页面时遇到了麻烦,它只显示没有样式的PartialView。

如何才能让整个页面呈现而不仅仅是PartialView?

下面是我查看和控制器的简单代码。

查看/刨光/ 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);
    }

    [...]
}

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。我很确定这不是最好的方法,但它有效。

如果已设置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会被独立加载,而我只返回与Index相同的视图,其中包含新ViewModel }}

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;
}