【问题标题】:Render Partial within a Partial MVC在部分 MVC 中渲染部分
【发布时间】:2017-05-31 16:15:02
【问题描述】:

我有 2 个局部视图,每个视图都有一个与之关联的不同视图模型。 第一个名为“AccountNamesPartial”的部分视图:

@using GACharts.Models.IntergratedAccount;
@model UpdateAccount
@for (int i = 0; i < Model.Accounts.Count(); i++)
{
<li>
    <label>
        @Html.HiddenFor(model => Model.Accounts[i].Id)
        @Html.CheckBoxFor(model => Model.Accounts[i].Selected)
        @Model.Accounts[i].Name
    </label>
</li>
}

所以上面的部分视图是我想要在我的第二个部分视图中 @Html.RenderPartial("AccountNamesPartial") :

@model GACharts.Models.ReportViewModel
<select class="form-control" id="ChartViewId" name="ChartViewId">
                        <option>Select View</option>
@{Html.RenderPartial("AccountNamesPartial", new GACharts.Models.IntergratedAccount.UpdateAccount());}
</select>

我不再收到堆栈跟踪错误,但数据不会出现在第二个局部视图上。有什么想法/建议可以让它工作吗?

【问题讨论】:

  • 看起来您正在初始化UpdateAccount 的新实例并将其传递给局部视图。由于它是一个新实例,它不会有任何数据。

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


【解决方案1】:

渲染一个表单来进行更新必然需要你获取你正在更新的实际对象来获取它的数据。如果您想继续使用局部视图,这意味着您需要在您的 ReportViewModel 上已经存在 UpdateAccount 视图模型:

public class ReportViewModel
{
    ...

    public UpdateAccount UpdateAccount { get; set; }
}

然后,您将在返回视图之前将其填充到您的操作中:

var account = // fetch, from DB, for example
reportModel.UpdateAccount = new UpdateAccount { /* map properties over here */ };

然后,在你的部分:

@Html.Partial("AccountNamesPartial", Model.UpdateAccount)

或者,您可以使用子操作:

[ChildActionOnly]
public ActionResult AccountNames()
{
    var account = // fetch, from DB, for example
    var model = new UpdateAccount { /* map properties */ };
    return PartialView("AccountNamesPartial", model);
}

然后,在你的部分:

@Html.Action("AccountNames")

【讨论】:

    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    相关资源
    最近更新 更多